Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
921 views
in Technique[技术] by (71.8m points)

.net - Why does the following doesn't compile? (involves generics and inheritance in c#)

This compiles:

    class ReplicatedBaseType
    {
    }

    class NewType: ReplicatedBaseType
    {
    }

    class Document
    {
    ReplicatedBaseType BaseObject;

    Document()
    {
     BaseObject = new NewType();
    }
}

But this does not:

    class DalBase<T> : where T: ReplicatedBaseType
    {
    }

    class DocumentTemplate
    {
    DalBase<ReplicatedBaseType> BaseCollection;
    DocumentTemplate ()
    {
    BaseCollection= new DalBase<NewType>(); // Error in this line. It seems this is not possible
    }
    }

What's the reason?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Andrey says, you want (generic) covariance. However:

  • Generic variance is only supported in C# 4
  • Generic variance isn't supported on classes
  • In your real life case, this may be unsafe.

To go into the final point, suppose DalBase<T> has this method:

void AddEntity(T entity)

Now you've got something like this which you want to be able to compile - but would obviously be dangerous:

DalBase<Fruit> fruitDal = new DalBase<Banana>();
fruitDal.AddEntity(new Apple());

The second line would have to compile - so for this to fail at compile time, it has to be the first line which would fail.

I gave an hour long talk on generic variance recently which you may find useful if you want to know more - see the NDC 2010 video page and search for "variance". Alternatively you could read Eric Lippert's blog posts on the topic - but be aware that that will probably take longer than an hour ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...