在泛型方法中使用实例的方法

Eli*_*Eli 0 c# generics

我的代码是这样的:

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!

Jon*_*eet 5

当然,他们都实施了这个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)

接口的解决方案是远吸尘器虽然在可行.