我在理解如何在现实世界中使用协方差和逆变时遇到了一些麻烦.
到目前为止,我见过的唯一例子是同样的旧数组示例.
object[] objectArray = new string[] { "string 1", "string 2" };
Run Code Online (Sandbox Code Playgroud)
很高兴看到一个允许我在开发过程中使用它的例子,如果我能看到它在其他地方使用的话.
我正在使用.NET框架,我真的希望能够创建一个我所有网站都使用的自定义类型的页面.当我尝试从控件访问页面时出现问题.我希望能够返回我的特定类型的页面而不是默认页面.有没有办法做到这一点?
public class MyPage : Page
{
// My own logic
}
public class MyControl : Control
{
public MyPage Page { get; set; }
}
Run Code Online (Sandbox Code Playgroud) 我的理解是在C#中为泛型指定方差发生在类型声明级别:当您创建泛型类型时,您指定类型参数的方差.另一方面,在Java中,指定了使用泛型的方差:当您创建某个泛型类型的变量时,您可以指定其类型参数的变化方式.
每种选择的优缺点是什么?
有谁知道为什么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<Order>
{
public Guid? Id { get; set; }
public String ProductName { get; set; }
public double Price { get; set; }
public virtual Order Build()
{
if(Id == null || ProductName == null || Price == null)
throw new InvalidOperationException("Missing required data!");
return …Run Code Online (Sandbox Code Playgroud) 在接口方面,我不清楚C#中Covariance的概念.严格基于我下面的例子,这是协方差的一个例子,请描述原因或原因.
class Program
{
static void Main()
{
ICarInterface car = new Car();
}
}
interface ICarInterface
{
void Start();
}
class Car : ICarInterface
{
public void Start()
{
}
}
Run Code Online (Sandbox Code Playgroud)