在C#中将通用类型参数转换为特定类型 [英] Cast generic type parameter to a specific type in C#

查看:118
本文介绍了在C#中将通用类型参数转换为特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您需要将泛型类型参数转换为特定类型,我们可以将其转换为对象并进行如下转换,

If you need to cast a generic type parameter to a specific type we can cast it to a object and do the casting like below,

void SomeMethod(T t)
{
    SomeClass obj2 = (SomeClass)(object)t;
}

有没有比将其强制转换为对象然后再转换为特定类型更好的方法了?

Is there a better way to achieve this rather than casting it to a object and then to a specific type.

问题

我有一个接受泛型类型参数的泛型函数,在函数内部基于类型检查,我进行了如下操作

I have a generic function which accepts a generic type parameter, inside the function based on a type checking I do some operations like below

    void SomeMethod(T t)
    {
        if (typeof(T).Equals(typeof(TypeA)))
        {
            TypeA = (TypeA)(object)t;
            //Do some operation
        }
        else if (typeof(T).Equals(typeof(TypeB)))
        {
            TypeB = (TypeB)(object)t;
            //Do some operation
        }
    }

推荐答案

一个更好的设计是在类型T和您希望在方法中使用的类(在本例中为SomeClass)之间施加约束.

A better design is to put a constraint on it that is common between type T and the class you want to expect in your method, in this case SomeClass.

class SomeConsumer<T> where T : ISomeClass
{
    void SomeMethod(T t)
    {
        ISomeClass obj2 = (ISomeClass) t;
    }
}

interface ISomeClass{}

class SomeClass : ISomeClass {}


基于问题的编辑进行编辑

那是糟糕的设计.尝试将操作"移到类本身中,以便调用者不必知道类型.如果这不可能实现,请分享更多正在执行的操作,但是您想要完成的是您没有一堆if/else语句,其执行取决于要传递给该方法的对象的类型.


Edit based on edit of Question

That is bad design. Try to move that "operation" into the class itself so the caller does not have to know the type. If that is not possible share more of what is being done, what you want to accomplish though is that you do not have a stack of if/else statements where execution depends on the type of object being passed in to the method.

class SomeConsumer<T> where T : ISomeClass
{
    void SomeMethod(T t)
    {
        ISomeClass obj2 = (ISomeClass) t;
        // execute
        t.Operation();
    }
}

interface ISomeClass{
    void Operation();
}

class SomeClass : ISomeClass {
    public void Operation(){/*execute operation*/}
}

这篇关于在C#中将通用类型参数转换为特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆