简体   繁体   English

通过类型动态设置泛型类中的静态字段

[英]Set static field in generic class by type dynamically

I have a generic class and static field in it. 我有一个通用类和静态字段。

public class SomeGenericClass<T> : ISomeInterface<T> where T : SomeClass
{
    public static ISomeInterface<T> _someField;
}

And when I want to change value of this field, I have to change it for each type like this 当我想更改该字段的值时,必须为每种类型更改它

var value = ...;
SomeGenericClass<Type1>._someField = value;
SomeGenericClass<Type2>._someField = value;
// ...
SomeGenericClass<Type3>._someField = value;

Is it possible to make it in loop, if I have array of types? 如果我有类型数组,是否可以使其循环? I would like to see something like this 我想看到这样的东西

Type[] types = ... //Array of types
foreach(type in types){
    SomeGenericClass<type>._someField = value;
}

Or something like that. 或类似的东西。

You can do this by reflection. 您可以通过反射来做到这一点。 First get the actual type: 首先获取实际类型:

var type = typeof(SomeGenericClass<>).MakeGenericType(theTypeArgument);

Now you can call GetField on that type in order to get the field: 现在,您可以在该类型上调用GetField以获取字段:

var field = type.GetField("_someField");

Next set the value. 接下来设置值。 Notice that the first parameter passed to SetValue is null , because the field is static : 注意,传递给SetValue的第一个参数为null ,因为该字段是static

field.SetValue(null, value);

Finally wrap this into a loop, eg: 最后,将其包装成一个循环,例如:

foreach(var t in types)
{
    var type = typeof(SomeGenericClass<>).MakeGenericType(t);
    var field = type.GetField("_someField");
    field.SetValue(null, value);
}

Of course you should also add some checks to avoid NullReferenceException . 当然,您还应该添加一些检查以避免NullReferenceException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM