C#在泛型类中访问类型T的静态属性 [英] C# accessing a static property of type T in a generic class

查看:84
本文介绍了C#在泛型类中访问类型T的静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完成以下场景,通用TestClassWrapper将能够访问它所组成的类的静态属性(它们都将从TestClass派生).像这样:

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 from TestClass). Something like:

public class TestClass
{
    public static int x = 5;
}

public class TestClassWrapper<T> where T : TestClass
{
    public int test()
    {
        return T.x;
    }
}

给出错误:'T'是一个'type parameter',在给定的上下文中无效.

有什么建议吗?

推荐答案

基本上,至少不能没有反射.

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...

这篇关于C#在泛型类中访问类型T的静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆