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
302 views
in Technique[技术] by (71.8m points)

c# - Type cannot be used as type parameter 'T' in the generic type or method - Why?


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

1 Reply

0 votes
by (71.8m points)

As an example of why you can't do this, imagine that in addition to FooModel and FooModelItem, you had BarModelItem. Now let's say you do this:

IModel<FooModelItem> fooModel = new FooModel();
IModel<IModelItem> iModel = fooModel;
iModel.Items = new List<BarModelItem>(new BarModelItem());

FooModelItem fooModelItem = fooModel.Items.First();

If this was valid code, you'd be in trouble, because the item you'd get back in the last line would not in fact be a FooModelItem but a BarModelItem!

If you read each line carefully, you will see that the only possible wrong line is the second one. This demonstrates why an IModel<FooModelItem> can't be assigned to an IModel<IModelItem>, even though FooModelItem : IModelItem. Not being able to do that assignment is exactly why your method call fails.

You can look into generic covariance and contravariance to see how this can be avoided in some cases, though it won't help in your particular situation without modifying your model.


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

...