![](/img/trans.png)
[英]Using interface with contravariant type as a return type of a method in an interface with covariant type
[英]How to covariant/contravariant in override virtual method which implements from interface?
我想在從接口實現的覆蓋虛方法中做contravariance
,我試過ICloneTo<in T>
和ICloneTo<out T>
都得到編譯錯誤,如下代碼:
interface ICloneTo<T> {
void CloneTo(T obj);
}
abstract class Base : ICloneTo<Base> {
public string BaseProperty { get; set; }
public virtual void CloneTo(Base obj) {
obj.BaseProperty = BaseProperty;
}
}
class A : Base {
public string AProperty { get; set; }
public override void CloneTo(A obj /* Contravariance to A */) {
base.CloneTo(obj);
obj.AProperty = AProperty;
}
}
C#中方法重寫此時沒有參數逆變。
這是我發現的最接近討論的內容: https://github.com/do.net/csharplang/discussions/3562
然而,通過一些通用的欺騙,你可以想出:
interface ICloneTo<T>
{
void CloneTo(T obj);
}
abstract class Base<T> : ICloneTo<T>
where T : Base<T>
{
public string BaseProperty { get; set; }
public virtual void CloneTo(T obj)
{
obj.BaseProperty = BaseProperty;
throw new NotImplementedException();
}
}
class A : Base<A>
{
public string AProperty { get; set; }
public override void CloneTo(A obj /* Contravariance to A */)
{
base.CloneTo(obj);
obj.AProperty = AProperty;
}
}
盡管可能有更好的方法來解決您要解決的任何問題...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.