开发者

Creating generic method and using type parameter

开发者 https://www.devze.com 2022-12-20 17:29 出处:网络
I have created this method which is an object factory: public static T GetService<T>(T serviceInterface)

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 inte开发者_JS百科rface: doing

T.Equals(typeof(ILookupService)) 

gives compiler error: 'T' is a 'type parameter', which is not valid in the given context.

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

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).

So,

typeof(T).Equals(typeof(ILookupService))


Could the is operator be applicable here?


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

精彩评论

暂无评论...
验证码 换一张
取 消