简体   繁体   English

确定属性类型是否为泛型类型参数

[英]Determine if a property type is a generic type argument

Say you have the class: 假设您有课程:

public class GenericModel<T1, T2>
{
    public T1 Model1 { get; set; }
    public T2 Model2 { get; set; }
}

How can you tell using reflection that the type of Model1 is generic argument T1 and the type of Model2 is generic argument T2? 您如何使用反射来判断Model1的类型是通用参数T1,而Model2的类型是通用参数T2?

I'm looking for a property or something that will tell me that Model1's type maps to typeof(GenericModel<,>).GetGenericArguments()[0] 我正在寻找属性或某些可以告诉我Model1的类型映射到typeof(GenericModel<,>).GetGenericArguments()[0]

Simple: 简单:

var model1Type = typeof(GenericModel<,>).GetProperty("Model1").PropertyType;
var model2Type = typeof(GenericModel<,>).GetProperty("Model2").PropertyType;

Then the values of model1Type.IsGenericParameter & model2Type.IsGenericParameter will both be true indicating that you've got the generic parameter type for the properties. 然后, model1Type.IsGenericParametermodel2Type.IsGenericParameter的值都model1Type.IsGenericParameter true指示您已获得属性的通用参数类型。

Also, model1Type.Name == "T1" & model2Type.Name == "T2" . 同样, model1Type.Name == "T1"model2Type.Name == "T2"


If you have a specific instance, such as var instance = new GenericModel<int, int>(); 如果您有特定的实例,例如var instance = new GenericModel<int, int>(); , then you can do this to get the generic name of a property out: ,那么您可以执行以下操作以获取属性的通用名称:

var instanceModel1TypeName =
    instance
        .GetType()
        .GetGenericTypeDefinition()
        .GetProperty("Model1")
        .PropertyType
        .Name;

// instanceModel1TypeName == "T1"

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

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