C#中的泛型和继承 [英] Generics and inheritance in C#

查看:202
本文介绍了C#中的泛型和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个E-R设计器生成的实体类,我已经修改了一点。这是声明:

  public abstract partial class Preference< T> :EntityObject,IPreference< T> 

然后有另一个实体类声明如下:

  public partial class BoolPref:Preference< bool> 

so BoolPref 继承自偏好< BOOL>
现在我有这个生成的属性:

  public ObjectSet<首选项< object>>偏好
{
get
{
if((_Preferences == null))
{
_Preferences = base.CreateObjectSet<首选项< object>> (优先);
}
return _Preferences;
}
}
private ObjectSet<首选项< object>> _优先;

当我尝试添加新的BoolPref到这个ObjectSet如下

  context.Preferences.AddObject(new BoolPref()); 

我收到编译时错误。



如何将BoolPref的实例添加到首选项? mystake在哪里?

解决方案

假设偏好< T> read-write属性叫做T型,现在假设类型系统按照你想要的方式工作:

  var set = new ObjectSet< Preference< object>>(); 
set.Add(new Preference< bool>());
set.First()。Value =hello;

在编译时这是合法的,因为set.First()。Value具有编译时间类型的对象,而不是布尔。但是在运行时,它的类型是bool,而你刚刚调用一个setter,它需要一个bool并传递一个字符串,破坏CLR中的内存,然后崩溃并死亡。



这就是为什么这是不合法的。在C#4中,只有在普遍类型为接口或委托的情况下才可以具有泛型协方差和逆变性,并且只有在引用类型不同的参数类型时才可以使用。


I have entity class generated by E-R designer that I have modified a little. This is declaration:

public abstract partial class Preference<T> : EntityObject, IPreference<T>

Then there is another entity class declared as follows:

public partial class BoolPref : Preference<bool>

so BoolPref inherits from Preferences<bool>. Now I have this generated property:

public ObjectSet<Preference<object>> Preferences
    {
        get
        {
            if ((_Preferences == null))
            {
                _Preferences = base.CreateObjectSet<Preference<object>>("Preferences");
            }
            return _Preferences;
        }
    }
    private ObjectSet<Preference<object>> _Preferences;

When I try to add new BoolPref to this ObjectSet as follows

context.Preferences.AddObject(new BoolPref ());

I get compile time error.

How can I add instances of BoolPref to Preferences ? Where is the mystake ?

解决方案

Suppose Preference<T> has a read-write property called Value of type T. Now suppose the type system works the way you'd like it to:

var set = new ObjectSet<Preference<object>>();
set.Add(new Preference<bool>());
set.First().Value = "hello"; 

That's legal at compile time because set.First().Value has compile time type of object, not bool. But at runtime it is of type bool, and you just called a setter that takes a bool and passed a string, corrupting memory in the CLR which then crashes and dies horribly.

That's why this is not legal. In C# 4 you can have generic covariance and contravariance only if it is provably typesafe, and only if the generic type is an interface or delegate, and only if the varying type argument is of reference type.

这篇关于C#中的泛型和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆