C# PropertyInfo(通用)

标签 c# reflection

假设我有这门课:

class Test123<T> where T : struct
{
    public Nullable<T> Test {get;set;}
}

和这个类

class Test321
{
   public Test123<int> Test {get;set;}
}

所以对于这个问题,假设我想通过反射创建一个 Test321 并为“Test”设置一个值,我如何获得通用类型?

最佳答案

由于您是从 Test321 开始的,因此获取类型的最简单方法是从属性:

Type type = typeof(Test321);
object obj1 = Activator.CreateInstance(type);
PropertyInfo prop1 = type.GetProperty("Test");
object obj2 = Activator.CreateInstance(prop1.PropertyType);
PropertyInfo prop2 = prop1.PropertyType.GetProperty("Test");
prop2.SetValue(obj2, 123, null);
prop1.SetValue(obj1, obj2, null);

或者你的意思是你想找到T

Type t = prop1.PropertyType.GetGenericArguments()[0];

关于C# PropertyInfo(通用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1320934/

相关文章:

C# - 使用 Lambda 创建多线程

java - 使用java反射的ClassnotFound异常

c# - 如何根据名称获取属性值

c# - 创建一个没有 0 值的 C# 枚举实例

c# - 按值或引用返回?

c# - Roslyn - 使用 CSharpCompilation 编译程序集,以便在 CSharpCompilation 编译的另一个程序中使用

c# - 有可能通过反射(reflection)来做到这一点吗?

reflection - Groovy:如何获取在基类中声明的属性

c# - ExecuteReader 不返回任何内容

c# - C# 在图像上绘制字符串时如何根据图像大小调整文本大小