我刚开始使用泛型,并想知道如何在类方法中访问类的T?让我们拿一些代码来更好地解释我想要做的事情:
public class RegisterResult<T> where T : IRegisterable
{
public bool Success { get; set; }
public string Entity { get; set; }
public string ErrorMessage { get; set; }
//Want to avoid this, by using generics:
/*public static RegisterResult UserSuccess = new RegisterResult(true, "User", "");
public static RegisterResult DeviceSuccess = new RegisterResult(true, "Device", "");
public static RegisterResult DeviceDataSucces = new RegisterResult(true, "DeviceData", "");*/
public RegisterResult(bool success, string errmsg)
{
this.Success = success;
//The following line does not work, so how can I reach that?
this.Entity = T.GetType().Name;
this.ErrorMessage = errmsg;
}
}
非常感谢你们所有有用且意义深远的答案!
更新:Visual Studio的错误消息
“T”是“类型参数”,在给定的上下文中无效
答案 0 :(得分:7)
这很简单:
this.Entity = typeof(T).Name;