简体   繁体   English

创建泛型方法并使用类型参数

[英]Creating generic method and using type parameter

I have created this method which is an object factory: 我创建了这个方法,它是一个对象工厂:

public static T GetService<T>(T serviceInterface)
{
    if (serviceInterface.Equals(typeof(IMemberService)))
    {
        return (T)(object)new MemberService();
    }
    else if (serviceInterface.Equals(typeof(ILookupService)))
    {
        return (T)(object)new LookupService();
    }
    throw new ArgumentOutOfRangeException("No action is defined for service interface " + serviceInterface.Name);
}

Now, I would like to go further and eliminate the need for "serviceInterface" parameter, but my problem is - I don't know how to compare type parameter T to an interface: doing 现在,我想进一步消除对“serviceInterface”参数的需求,但我的问题是 - 我不知道如何将类型参数T与接口进行比较:

T.Equals(typeof(ILookupService)) 

gives compiler error: 'T' is a 'type parameter', which is not valid in the given context. 给出编译器错误:'T'是'type parameter',在给定的上下文中无效。

Any ideas how could I compare a type parameter to an interface? 任何想法如何将类型参数与接口进行比较?

Thank you, Andrey 谢谢,安德烈

You can use typeof(T) to get a Type object back which could replace the use of serviceInterface 您可以使用typeof(T)来获取Type对象,这可以替换serviceInterface的使用

For example 例如

public static T GetService<T>()
{
    Type serviceInterface = typeof(T);
    if (serviceInterface.Equals(typeof(IMemberService)))
    {
        return (T)(object)new MemberService();
    }
    else if (serviceInterface.Equals(typeof(ILookupService)))
    {
        return (T)(object)new LookupService();
    }
    throw new ArgumentOutOfRangeException("No action is defined for service interface " + serviceInterface.Name);
}

Use typeof(T) . 使用typeof(T)

So, 所以,

typeof(T).Equals(typeof(ILookupService))
if (typeof(IMemberService).IsAssignableFrom(typeof(T)))
{}
else if (typeof(ILookupService).IsAssignableFrom(typeof(T)))
{}

请问就是运营商适用吗?

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

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