C# accessing a static property of type T in a generic class

前端 未结 7 1475
后悔当初
后悔当初 2020-12-16 09:30

I am trying to accomplish the following scenario that the generic TestClassWrapper will be able to access static properties of classes it is made of (they will all derive fr

相关标签:
7条回答
  • 2020-12-16 10:07

    You can't, basically, at least not without reflection.

    One option is to put a delegate in your constructor so that whoever creates an instance can specify how to get at it:

    var wrapper = new TestClassWrapper<TestClass>(() => TestClass.x);
    

    You could do it with reflection if necessary:

    public class TestClassWrapper<T> where T : TestClass
    {
        private static readonly FieldInfo field = typeof(T).GetField("x");
    
        public int test()
        {
            return (int) field.GetValue(null);
        }
    }
    

    (Add appropriate binding flags if necessary.)

    This isn't great, but at least you only need to look up the field once...

    0 讨论(0)
提交回复
热议问题