C#以自己的方法访问泛型类的T.

时间:2015-05-21 01:47:53

标签: c# generics

我刚开始使用泛型,并想知道如何在类方法中访问类的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”是“类型参数”,在给定的上下文中无效

1 个答案:

答案 0 :(得分:7)

这很简单:

this.Entity = typeof(T).Name;