簡體   English   中英

無法返回約束泛型的具體實現

[英]Cannot return concrete implementation of constraint generic

我在仿制葯方面遇到了一些問題,我沒有看到我的錯誤。

鑒於此代碼:

public interface IMyInterface { }

public class MyImplementation : IMyInterface { }

public interface IMyFactory<T> where T : class, IMyInterface
{
    T Create();
}

public class MyFactory<T> : IMyFactory<T> where T : class, IMyInterface
{
    public T Create()
    {
        // Complex logic here to determine what i would like to give back
        return new MyImplementation(); // <--- red squigglies - Cannot implicitly convert type 'ConsoleApp18.MyImplementation' to 'T'
    }
}

如果我像這樣使用它return new MyImplementation() as T; 有用。 不再存在錯誤。

如果我像這樣使用它return (T)new MyImplementation(); 我得到一個代碼建議刪除不必要的演員。 (是的,這也是我的想法,為什么不能返回具體的實現,因為它與T兼容?)​​並且第一個錯誤(不能隱式轉換...)仍然存在。

那么為什么我會得到這個錯誤以及返回具體實現的正確實現是什么?

我在仿制葯方面遇到了一些問題,我沒有看到我的錯誤。

你的錯誤是使用泛型。 鑒於您顯示的代碼,您根本不需要它們。 工廠應返回IMyInterface而不是T

public interface IMyFactory
{
    IMyInterface Create();
}

public class MyFactory : IMyFactory
{
    public IMyInterface Create()
    {
        // Complex logic here to determine what i would like to give back
        return new MyImplementation();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM