我不確定這正是你所需要的,但是這可以讓你在不使用反射的情況下從InterfaceMethod調用AnotherMethod。它仍然使用Convert.ChangeType。
這個想法是通過約束(這裏是Tin)來實現泛型類的實現。然後,將InterfaceMethod的無約束類型T轉換爲Tin。最後,您可以使用約束類型調用AnotherMethod。以下工作正常與字符串。
public interface ITest
{
T InterfaceMethod<T> (T arg);
}
public interface ITest2
{
U AnotherMethod<U>(U arg) where U : class;
}
public class Test<Tin> : ITest, ITest2 where Tin : class
{
public T InterfaceMethod<T> (T arg)
{
Tin argU = arg as Tin;
if (argU != null)
{
Tin resultU = AnotherMethod(argU);
T resultT = (T)Convert.ChangeType(resultU,typeof(T));
return resultT;
}
return default(T);
}
public U AnotherMethod<U> (U arg) where U : class { return arg; }
}
是什麼AnotherMethod()做有T?如果你想打開它,只需先將它投射到一個物體上。? –
2012-07-25 02:05:26
不知道這對我有幫助,因爲我收到了關於T需要成爲引用類型的編譯錯誤。 – techphoria414 2012-07-25 02:13:27