问题
Considering there is a method
static IEnumerable<IComparable> q()
{
return new List<string>();
}
I am trying to achieve the same but on my own classes and as a result i receive casting error cs0266
I tried to cast this way return (Common<Message>)new A();
but it results InvalidCastException
interface Common<T> where T : Message
{
T Source { get; }
void Show();
}
interface Message
{
string Message { get; }
}
class AMsg : Message
{
public string Message => "A";
}
class A : Common<AMsg>
{
public AMsg Source => new AMsg();
public void Show() { Console.WriteLine(Source.Message); }
}
static Common<Message> test()
{
return new A(); //CS0266
}
How can the method return different generics that implement same interface?
回答1:
IEnumerable
is covariant which is why the first block of code works. To do the same thing you need to make your T
type paramater covariant by adding the out modifier:
interface Common<out T> where T : Message
{
T Source { get; }
void Show();
}
Now you can write code like this:
Common<Message> x = new A();
来源:https://stackoverflow.com/questions/57490565/return-different-generics-that-implement-same-interface