如何确定类实例上泛型参数的值

时间:2008-09-22 06:04:03

标签: c# generics reflection

我有一个标记接口定义为

public interface IExtender<T>
{
}

我有一个实现IExtender

的类
public class UserExtender : IExtender<User>

在运行时,我将UserExtender类型作为我的评估方法的参数

public Type Evaluate(Type type) // type == typeof(UserExtender)

如何让我的Evaluate方法返回

typeof(User)

基于运行时评估。我确信会有反思,但我似乎无法破解它。

(我不确定如何说出这个问题。我希望它足够清楚。)

3 个答案:

答案 0 :(得分:1)

有一个示例可以执行您在GetGenericTypeDefinition method的MSDN文档中描述的内容。它使用GetGenericArguments method

Type[] typeArguments = t.GetGenericArguments();
Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length);
foreach (Type tParam in typeArguments)
{
    Console.WriteLine("\t\t{0}", tParam);
}

在您的示例中,我认为您希望将t替换为this。如果这不能直接起作用,您可能需要使用GetInterfaces method执行某些操作来枚举类型的当前接口,然后从接口类型中GetGenericArguments()

答案 1 :(得分:1)

我根据提供的一些花絮这样做了。可以使得在接口上处理多个泛型参数更加健壮......但我不需要它;)

private static Type SafeGetSingleGenericParameter(Type type, Type interfaceType)
{
    if (!interfaceType.IsGenericType || interfaceType.GetGenericArguments().Count() != 1)
        return type;

    foreach (Type baseInterface in type.GetInterfaces())
    {
        if (baseInterface.IsGenericType &&
                baseInterface.GetGenericTypeDefinition() == interfaceType.GetGenericTypeDefinition())
        {
            return baseInterface.GetGenericArguments().Single();
        }
    }

    return type;
}

答案 2 :(得分:1)

我完全不同于其他答案阅读你的问题。

如果评估签名可以更改为:

public Type Evaluate<T>(IExtender<T> it)
{
    return typeof(T);
}

这不需要更改调用代码,但确实要求参数类型为IExtender<T>,但您可以轻松获取T类型:

// ** compiled and tested    
UserExtender ue = new UserExtender();
Type t = Evaluate(ue);

当然,它不像仅仅使用Type参数那样通用,但这是对问题的不同看法。另请注意,Security Considerations for Reflection [msdn]

相关问题