[英]How to call a method with a generic constraint using a type parameter without the constraint?
[英]How to call generic method with stronger constraint?
namespace Test
{
#region Not my code
public interface IAdditional
{
}
public interface ISome
{
ISomeOther<T> GetSomeother<T>() where T : class;
}
public interface ISomeOther<T> where T : class
{
void DoFoo(T obj);
}
public class AnotherClass<T> where T : class
{
}
public static class StaticClass
{
public static void DoBar<T>(AnotherClass<T> anotherClass, T obj) where T : class, IAdditional
{
}
}
#endregion
#region MyCode
public class SomeOtherImp<T> : ISomeOther<T> where T : class, IAdditional //Have to add IAdditional constraint to call StaticClass.DoBar
{
private AnotherClass<T> _anotherClass;
public void DoFoo(T obj)
{
StaticClass.DoBar<T>(_anotherClass, obj); //I do need to call StaticClass.DoBar here....
}
}
public class ISomeImp : ISome
{
public ISomeOther<T> GetSomeother<T>() where T : class
{
return new SomeOtherImp<T>(); //Can't do this no IAdditional constraint on T
}
}
#endregion
}
我被迫將IAdditional
添加到SomeOtherImp
以便能夠調用StaticClass.DoBar
。
現在,我無法使用SomeOtherImp<T>
實現ISome
。
您的意思是您希望能夠調用Get方法嗎? 如果可以編輯ISome界面,請嘗試以下操作:
public interface ISome
{
T Get<T>() where T:class, ISomeInterface
}
...否則,您將不得不使用反射:
public class Foo : ISome
{
public T Get<T>() where T:class
{
if (!typeof(ISomeInterface).IsAssignableFrom(typeof(T))) throw new Exception();
return (T)typeof(SomeStaticClass).GetMethod("Create").MakeGenericMethod(new [] {typeof(T)}).Invoke();
}
}
你可以這樣做
public class Foo : ISome
{
public T Get<T>() where T : class
{
return SomeStaticClass.Create<ISomeInterface>() as T;
}
}
如果返回null,則傳入的不是ISomeInterface類型。
看來您正在嘗試實施工廠設計模式。 看一下下面的代碼。 我從SomeClass的限制中刪除了該接口。 它可以編譯並且可以工作。 我認為ISome及其實現Foo類已過時。
public static class SomeStaticClass
{
public static T Create<T>() where T:class
{
//Replace with actual construction of T
return (T)(new object());
}
}
public interface ISome
{
T Get<T>() where T : class;
}
public class Foo : ISome
{
public T Get<T>() where T:class
{
return SomeStaticClass.Create<T>();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.