有没有办法在C#中存储指向属性的指针?

时间:2019-07-11 16:07:22

标签: c# properties

例如,如果我想做这样的事情:

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。

2 个答案:

答案 0 :(得分:1)

我没有找到执行此操作的任何本机方法,但是您可以创建一个可以执行此操作的结构。 免责声明:我确实实现了它,因为这样做很有趣。我没有进行测试,所以它只是一个想法,我怀疑它是否有效。

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));

答案 1 :(得分:0)

  

是否可以在C#中存储指向属性的指针?

不,基本上。

如果它是ref返回属性,则可以很接近,但也不能存储ref-您只能在堆栈上使用它。

相关问题