简体   繁体   English

铸造仿制药

[英]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. 由于CreateOjectSet方法返回null。

ps The code above is trying to fake the System.Data.Objects.ObjectContext.CreateObjectSet method. ps上面的代码试图伪造System.Data.Objects.ObjectContext.CreateObjectSet方法。

In your example, FObjectSet does not appear to inherit from ObjectSet. 在您的示例中,FObjectSet似乎不从ObjectSet继承。 It only implements the IObjectSet interface. 它只实现了IObjectSet接口。

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... 如果它确实从ObjectSet继承,那么在将它转换为ObjectSet之前你不需要将它强制转换为IObjectSet,事实上,你根本不需要将它转换为...

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> . 这不起作用,因为FObjectSet<T>不扩展ObjectSet<T> You could return IObjectSet<T> instead, but I don't know if that would do what you want. 您可以返回IObjectSet<T> ,但我不知道是否可以执行您想要的操作。

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

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