[英]Using an inherited generic type as an input to a method of a type constrained class
編輯:進行更改以使代碼更好地識別問題。
我正在調整蒙特卡洛模擬的性能,在該模擬中,將IComponent轉換為IProposition會造成瓶頸。 我已經提出了一個架構師來刪除鑄件,但是它沒有按預期工作。
TryDo中的方法調用會引發編譯器錯誤? (不能將參數類型“ IProposition”分配給參數類型“ T”)為什么? (IProposition滿足對T的約束)以及如何解決?
using System.Collections.Generic;
public interface IComponent<T> where T : IComponent<T>
{
HashSet<T> Inputs { get; }
}
public interface IProposition<T> : IComponent<T> where T : IComponent<T> { }
public interface IAnd<T> : IComponent<T> where T : IComponent<T> {}
class DoStuff<T> where T : IComponent<T>
{
private void DoIt(T component)
{
if (component is IAnd<T>)
foreach(T input in component.Inputs)
DoIt(input);
}
void TryDo(IProposition<T> proposition)
{
DoIt(proposition);
}
}
(我想出了一個單獨的解決方案,該解決方案使用單獨的類型'TP'表示IProposition-但似乎多余,因為IProposition當然是IComposition的子類)
我不確定要用這種模型完成什么工作,但是這段代碼可以編譯:
public interface IComponent<T> where T : IComponent<T> { }
public interface IProposition<T> : IComponent<T> where T : IComponent<T> { }
class DoStuff<T> where T : IComponent<T>
{
private void DoIt(T component)
{
}
void TryDo(T component, T proposition)
{
DoIt(component);
DoIt(proposition);
}
}
我不確定您是否完全了解泛型的工作原理。 您似乎有一個主意,但我真的不知道這樣的代碼有什么實際目的。
現在不要誤會我的意思,但是您應該花時間在更簡單的模型上研究泛型和c#。 代碼中的錯誤是由於僅向DoIt
方法提供了錯誤的類型而引起的,這是一個非常初學者的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.