为什么属性在编译方法时会出错?
public interface IFoo {}
public interface IBar<out T> where T : IFoo {}
public interface IItem<out T> where T: IFoo
{
// IEnumerable<IBar<T>> GetList(); // works
IEnumerable<IBar<T>> ItemList { get; set; } // Error!
}
Run Code Online (Sandbox Code Playgroud)
错误:
方差无效:类型参数"T"必须在"UserQuery.IItem <T> .ItemList"上具有矛盾的有效性.'T'是协变的.
该陈述是什么意思?
在C#中引用和输出参数,不能标记为变体.
1)是否意味着不能做以下事情.
public class SomeClass<R, A>: IVariant<R, A>
{
public virtual R DoSomething( ref A args )
{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
2)或者它是否意味着我不能拥有以下内容.
public delegate R Reader<out R, in A>(A arg, string s);
public static void AssignReadFromPeonMethodToDelegate(ref Reader<object, Peon> pReader)
{
pReader = ReadFromPeon;
}
static object ReadFromPeon(Peon p, string propertyName)
{
return p.GetType().GetField(propertyName).GetValue(p);
}
static Reader<object, Peon> pReader;
static void Main(string[] args)
{
AssignReadFromPeonMethodToDelegate(ref pReader);
bCanReadWrite = (bool)pReader(peon, "CanReadWrite");
Console.WriteLine("Press any key to quit...");
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
我试过(2)并且它有效.