[英]Return derived class instance instead of base class instance
I have an interface that looks like this 我有一个看起来像这样的界面
public interface SomeInterface<T, U>
where T : struct
where U : class
{
void Method1();
IDictionary<T, BaseClassItem<U>> GetDictionary();
}
I have one of the implementations like this 我有这样的实现之一
public class LruEvictor<T, U> : SomeInterface<T, U>
where T : struct
where U : class
{
private Dictionary<T, BaseClassItem<U>> _dictionary;
public void Evict()
{
}
public IDictionary<T, BaseClassItem<U>> GetDictionary()
{
_dictionary = new Dictionary<T, BaseClassItem<U>>();
return _dictionary;
}
}
In the above GetDictionary() method I would like to return a dictionary of type Dictionary<T, DerivedItem<U>>.
在上面的GetDictionary()方法中,我想返回一个
Dictionary<T, DerivedItem<U>>.
类型的Dictionary<T, DerivedItem<U>>.
Is that possible? 那可能吗? If yes how do I do it.
如果是,我该怎么做。
Given below is the derived class implementation. 下面给出了派生类的实现。
public class DerivedItem<U> : BaseClassItem<U>
where U : class
{
public DerivedItem(U value) :base(value)
{
}
public DateTime LastAccessed { get; private set; }
public override void OnAccessed()
{
LastAccessed = DateTime.Now;
}
}
Any input will be appreciated. 任何输入将不胜感激。
Thanks in advance. 提前致谢。
I'm fairly sure you can't do this, as it would break the type system. 我相当确定您不能这样做,因为它会破坏类型系统。
Consider the usual animal example: 考虑通常的动物示例:
public IDictionary<T, Animal> GetDictionary()
{
_dictionary = new Dictionary<T, Llama>();
return _dictionary; // Imagine you can do this
}
IDictionary<T, Animal> dict = GetDictionary();
dict.Add(MakeT(), new Horse()); // Ouch.
No, you can't do that. 不,你不能那样做。 A simple version of your question would be that given
一个简单的问题就是
class Base { }
class Derived : Base { }
is it possible to use IDictionary<T, Base> dict = new Dictionary<T, Derived>()
. 是否可以使用
IDictionary<T, Base> dict = new Dictionary<T, Derived>()
。
This is not possible because covariance rules of C# don't allow that. 这是不可能的,因为C#的协方差规则不允许这样做。 And for good reason because if it would work then you could simply add an object of type
Base
to the dictionary that should only accept Derived
objects. 这是有充分理由的,因为如果可以,那么您可以简单地将类型为
Base
的对象添加到仅应接受Derived
对象的字典中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.