我试图完成以下场景,通用TestClassWrapper将能够访问它所构成的类的静态属性(它们都将从TestClass派生).就像是:
public class TestClass
{
public static int x = 5;
}
public class TestClassWrapper<T> where T : TestClass
{
public int test()
{
return T.x;
}
}
Run Code Online (Sandbox Code Playgroud)
给出错误: 'T' is a 'type parameter', which is not valid in the given context.
有什么建议?
Jon*_*eet 28
基本上,你不能没有反思.
一种选择是将委托放在构造函数中,以便创建实例的人可以指定如何获取它:
var wrapper = new TestClassWrapper<TestClass>(() => TestClass.x);
Run Code Online (Sandbox Code Playgroud)
如有必要,你可以用反射做到这一点:
public class TestClassWrapper<T> where T : TestClass
{
private static readonly FieldInfo field = typeof(T).GetField("x");
public int test()
{
return (int) field.GetValue(null);
}
}
Run Code Online (Sandbox Code Playgroud)
(如有必要,添加适当的绑定标志.)
这不是很好,但至少你只需要查看一次......
当然你可以这样写:
public int test()
{
return TestClass.x;
}
Run Code Online (Sandbox Code Playgroud)
即使在一个非常重要的示例中,您也无法覆盖静态字段,因此始终会从已知的基类中调用它.
泛型不支持与静态成员相关的任何内容,因此这是行不通的。我的建议是:不要使其静态。假设该字段确实与特定相关T,您还可以使用反射:
return (int) typeof(T).GetField("x").GetValue(null);
Run Code Online (Sandbox Code Playgroud)
但我不推荐它。