开发者

C# Type Conversions for Generics Parameter

This is a rather elementary C# question; 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>?

I.e.

//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 t开发者_开发问答emplate<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

Edit: I ended up using a Cast similar to: bang(bee.Cast());


There is no guarantee that Generic<SubType> can actually be used as a replacement for 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.


.NET 3.5 doesn't have Covariance and Contravariance in Generics as MonkeyWrench indicated. 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();
    }
}


It should be, and is in .Net 4.0.

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


In .NET 3.5, I would handle something like this in a list like the following:

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜