简体   繁体   中英

Casting generics

Can someone help me with a work-around for this issue?

I have the following class:

public partial class FObjectSet<T> : IObjectSet<T> where T : class
{
...
}

I also have the following class:

public partial class FContext : IContext, IDisposable
{
    public ObjectSet<T> CreateObjectSet<T>() where T : class
    {
        var fakeObjectSet = new FObjectSet<T>();
        return (fakeObjectSet as IObjectSet<T>) as ObjectSet<T>;
    }
}

The CreateOjectSet method returns a null as the cast is not working.

ps The code above is trying to fake the System.Data.Objects.ObjectContext.CreateObjectSet method.

In your example, FObjectSet does not appear to inherit from ObjectSet. It only implements the IObjectSet interface.

If it did inherit from ObjectSet, you wouldn't need to cast it to a IObjectSet before casting it to an ObjectSet, in fact, you wouldn't need to cast it at all...

public partial class FObjectSet<T> : ObjectSet<T> where T : class
{
...
}

public partial class FContext : IContext, IDisposable
{
    public ObjectSet<T> CreateObjectSet<T>() where T : class
    {
        var fakeObjectSet = new FObjectSet<T>();
        return fakeObjectSet;
    }
}

This doesn't work because FObjectSet<T> doesn't extend ObjectSet<T> . You could return IObjectSet<T> instead, but I don't know if that would do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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