我的代码是这样的:
public T ReadState<T>(string file_path)
{
string file_content = ...read file..from file_path...
T state = ...xml deserialize...
state.SetSomething(); // <--the problem is here <--
return state;
}
Run Code Online (Sandbox Code Playgroud)
我想在各种对象类型上使用这个泛型方法.当然,他们都实施了这个SetSomething()方法
目前,编译器抱怨:
'T'不包含SetSomething()的定义......
TIA!
当然,他们都实施了这个
SetSomething()方法
然后你应该告诉编译器:
SetSomething()方法创建一个接口约束T实现该接口:
public T ReadState<T>(string file_path) where T : IYourNewInterface
Run Code Online (Sandbox Code Playgroud)如果你不能使类型都实现一个接口,最简单的解决方案可能是使用动态类型:
((dynamic) state).SetSomething();
Run Code Online (Sandbox Code Playgroud)
接口的解决方案是远吸尘器虽然在可行.
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |