0
刚开始泛型,想知道如何在类方法中访问类的T?让我们采取一些代码来更好地解释我想要做的事情:C#在自己的方法中访问泛型类的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;
}
}
非常感谢您提供所有帮助和意义的答案!
UPDATE:ERRORMESSAGE从Visual Studio
“T” 是 “类型参数”,并在给定的上下文无效
当你说那行不工作,你在那条线上看到了什么确切的错误信息和/或例外情况? –
谁投了这个问题?这似乎很适合我。 OP说他刚开始使用泛型,所以这是一个合理的问题。 – Enigmativity
对不起@JohnHodge,我添加了错误信息 –