2015-05-21 33 views
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” 是 “类型参数”,并在给定的上下文无效

+0

当你说那行不工作,你在那条线上看到了什么确切的错误信息和/或例外情况? –

+1

谁投了这个问题?这似乎很适合我。 OP说他刚开始使用泛型,所以这是一个合理的问题。 – Enigmativity

+0

对不起@JohnHodge,我添加了错误信息 –

回答

7

就算这样简单:

this.Entity = typeof(T).Name;