Tag: 协方差

在C#中引用和输出参数,不能标记为变体

该陈述是什么意思? 从这里 在C#中引用和输出参数,不能标记为变体。 1)是否意味着不能做以下事情。 public class SomeClass: IVariant { public virtual R DoSomething( ref A args ) { return null; } } 2)或者它是否意味着我不能拥有以下内容。 public delegate R Reader(A arg, string s); public static void AssignReadFromPeonMethodToDelegate(ref Reader pReader) { pReader = ReadFromPeon; } static object ReadFromPeon(Peon p, string propertyName) { return p.GetType().GetField(propertyName).GetValue(p); } static Reader pReader; static […]

关于子类返回类型的C#协方差

有谁知道为什么C#不支持协变返回类型? 即使在尝试使用接口时,编译器也会抱怨它是不允许的。 请参阅以下示例。 class Order { private Guid? _id; private String _productName; private double _price; protected Order(Guid? id, String productName, double price) { _id = id; _productName = productName; _price = price; } protected class Builder : IBuilder { public Guid? Id { get; set; } public String ProductName { get; set; } public double […]

为什么我不能将List 分配给List ?

我定义了以下类: public abstract class AbstractPackageCall { … } 我还定义了这个类的子类: class PackageCall : AbstractPackageCall { … } AbstractPackageCall还有其他几个子节点 现在我想进行以下调用: List calls = package.getCalls(); 但我总是得到这个例外: Error 13 Cannot implicitly convert type ‘System.Collections.Generic.List’ to ‘System.Collections.Generic.List’ 这里有什么问题? 这是Package#getCalls的方法 internal List getCalls() { return calls; }

Casting List – 协方差/逆变问题

给出以下类型: public interface IMyClass { } public class MyClass : IMyClass { } 我想知道如何将List转换为List ? 关于协方差/逆变主题,我并不完全清楚,但据我所知,由于这个原因,我不能仅仅清楚地列出清单。 我只能提出这个微不足道的解决方案; 缺乏优雅,浪费资源: … public List ConvertItems(List input) { var result = new List(input.Count); foreach (var item in input) { result.Add(item); } return result; } …. 你怎么能以更优雅/高效的方式解决它? ( 请注意,我需要.NET 2.0解决方案,但为了完整性,我也很高兴看到使用更新框架版本的更优雅的解决方案。 )