小编use*_*730的帖子

.NET 4.0 Cast通用接口

我有两个接口,其中一个是通用接口,只允许从第二个接口派生的类型.它们看起来像这样:

public interface IProvider<T> where T : IContent
{
    T getContent(int i);
    void addContent(T content);
}
public interface IContent
{
    string whatIAm();
}
Run Code Online (Sandbox Code Playgroud)

当然,我真正的界面更复杂,但它应该显示我的问题是什么.现在我为每个接口都有一个具体的类:

public class Provider : IProvider<FileContent> 
{
    public FileContent getContent(int i)
    {
        return null;
    }
    public void addContent(FileContent content)
    {
    }
}

public class FileContent : IContent{
    public string whatIAm(){
        return "FileContent";
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我想使用引用类型"IProvider",但演员出错...请看这个例子:

 static void Main(string[] args)
    {
        Provider p = new Provider(); //works
        IProvider<FileContent> pp = p as IProvider<FileContent>; //also works
        IProvider<IContent> ppp = …
Run Code Online (Sandbox Code Playgroud)

.net generics casting interface

4
推荐指数
1
解决办法
577
查看次数

标签 统计

.net ×1

casting ×1

generics ×1

interface ×1