在不知道Type参数的情况下转换为泛型 [英] Casting to a generic without knowing the Type parameter

查看:76
本文介绍了在不知道Type参数的情况下转换为泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎应该可行,但对于我的一生,我不记得怎么做.

假设我有一个类似的通用名称:

It seems like this should be possible, but for the life of me I can''t remember how.

Let''s say I have a generic like:

class jigger<T>
{
    public T DoSomething() {}
}


我有一些类,其中一些继承了


and I have classes, some of which inherit

class blick : jigger<string>
{
}


class flegh : jigger<bool>
{
}


class klipsh : jigger<int>
{
}


class smothy 
{
}


class gribb 
{
}


然后我要评估并投射:


and then I want to evaluate and cast:

var mixedbag = new object[]
{
    blick, flegh, klipsh, smothy, gribb
};

foreach(var i in mixedbag)
{
    // This is what I can't figure out:
    if(i is jigger<>)
        (i as jigger<>).DoSomething();
}

推荐答案

在这种情况下,我要做的是创建一个非通用的接口.似乎运作良好.当然有更多的东西要处理,但是仍然意味着您可以将不同类型的泛型保存在变量中.

What I do in this case is create an interface that is not generic. Seems to work well. Of course more stuff to deal with, but still means you can have generics of different types saved in a variable.

Interface IJigger<T>
{
    T DoSomething();
}

class jigger<T> : IJigger
{
    public T DoSomething() {}
}


foreach(var i in mixedbag)
{
    // This is what I can't figure out:
    if(i is IJigger)
        ((IJigger)i).DoSomething();
}



注意:使用(i as jigger<>) 确实不会给您带来任何好处.改为使用cast .如果(i as IJigger) 为null,则仍然会崩溃.



Note: Using (i as jigger<>) really buys you nothing. Use cast instead. If (i as IJigger) is null you crash anyway.


这篇关于在不知道Type参数的情况下转换为泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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