有没有办法在 C# 中存储指向属性的指针? [英] Is there a way to store a pointer to a property in C#?
本文介绍了有没有办法在 C# 中存储指向属性的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,如果我想做这样的事情:
For example, if I wanted to do something like this:
class Program
{
static void Main(string[] args)
{
var dictionary = new Dictionary<string, Property<AddressInfo>>
{
{ "f", (thing) => thing.Foo },
{ "o", (thing) => thing.Foo },
{ "o", (thing) => thing.Foo },
{ "b", (thing) => thing.Bar },
{ "a", (thing) => thing.Bar },
{ "r", (thing) => thing.Bar },
};
}
}
class Thing
{
public string Foo { get; set; }
public string Bar { get; set; }
}
否则我必须将 getter 和 setter 分别存储为 Func 和 Action.
Otherwise I have to store both the getter and the setter as a Func and an Action separately.
推荐答案
我没有找到任何本地方法来做到这一点,但您可以创建一个结构体来做到这一点.免责声明:我确实实施了它,因为这样做很有趣.我没有测试,所以只是提供一个想法,我怀疑它的效率.
I did not find any native way to do it but you can create a struct which would do it. Disclaimer: I did implement it because it was fun to do. I didn't test so it's just togive an idea and I doubt it's efficient.
public class PropertyHolder<T, Y>
{
private static object[] emptyArray = new object[0];
public PropertyHolder(Y instance, string propertyName)
{
var property = typeof(Y).GetProperty(propertyName);
var setMethod = property.SetMethod;
var getMethod = property.GetMethod;
Set = (t) => setMethod.Invoke(instance, new object[]{t});
Get = () => (T) getMethod.Invoke(instance, emptyArray);
}
public Action<T> Set { get; private set; }
public Func<T> Get { get; private set; }
}
你可以这样使用:
public class Toto
{
public int TheInt { get; set; }
}
var x = new Toto();
var propPointer = new PropertyHolder<int,Toto>(x, nameof(Toto.TheInt));
这篇关于有没有办法在 C# 中存储指向属性的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文