简体   繁体   English

泛型参数的C#类型转换

[英]C# Type Conversions for Generics Parameter

This is a rather elementary C# question; 这是一个相当基本的C#问题。 my apologies, but I haven't been able to find this elsewhere. 抱歉,但我无法在其他地方找到。

What is the best way to convert from Object<class> to Object<interface> ? Object<class>转换为Object<interface>的最佳方法是什么?

Ie

//fake interface
interface ignu {}

//fake class which implements fake interface
class bee : ignu {}

//function which accepts a generic with the interface
function bang(template<bee>) {}

//template type but with a class that implements the interface
template<bar> foo;

//trying to call the function, but compiler complains it can't implicitly convert
bang(foo); 

//compilers complains that it cannot convert from template<bee> to template<ignu>
bang((template<ignu>)bee)

Maybe I'm way off base, but this seems like it should work and be doable, but the solution is escaping me. 也许我离基础很远,但这似乎应该可行并且可行,但是解决方案正在逃避我。

Edit: Changed mygen to be template as I was using both to refer to the same thing which was confusing 编辑:将mygen更改为模板,因为我同时使用两者来指代令人困惑的同一件事

Edit: I ended up using a Cast similar to: bang(bee.Cast()); 编辑:我最终使用类似于以下的Cast:bang(bee.Cast());

There is no guarantee that Generic<SubType> can actually be used as a replacement for Generic<BaseType> . 无法保证Generic<SubType>实际上可以代替Generic<BaseType>

Consider this: 考虑一下:

List<int> intlist = new List<int>();
List<object> objlist = intlist; // compile error
objlist.Add("foo"); // what should be in intlist now?

What you are looking for is called co- and contra- variance. 您要寻找的是所谓的协方差和反方差。 They have been added in c#4. 它们已在c#4中添加。

It should be, and is in .Net 4.0. 它应该是,并且在.Net 4.0中。

Check this out: http://msdn.microsoft.com/en-us/library/dd799517.aspx 检查一下: http : //msdn.microsoft.com/en-us/library/dd799517.aspx

.NET 3.5 doesn't have Covariance and Contravariance in Generics as MonkeyWrench indicated. 正如MonkeyWrench指出的那样,.NET 3.5在泛型中没有协方差和协方差。 However, there are built in ways to do the casting necessary. 但是,存在一些进行必要铸造的方法。

class Program
{
    static void Main(string[] args)
    {
        List<ccc> c = new List<ccc>();
        c.Add(new ccc());

        List<iii> i = new List<iii>(c.Cast<iii>());
    }
}

interface iii
{
    void DoIt();
}

class ccc : iii
{
    public void DoIt()
    {
        throw new NotImplementedException();
    }
}

In .NET 3.5, I would handle something like this in a list like the following: 在.NET 3.5中,我将在类似以下的列表中处理类似的事情:

list<bar> myList = new list<bar>;
myList.Select<ignu>(x => x).ToList();

I would think it wouldn't be too hard to do something like that for a single object. 我认为为单个对象执行类似操作并不难。

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

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