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

Tob*_*ann 0 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

非常感谢所有有用且意义深远的答案!

更新:Visual Studio的错误消息

"T"是"类型参数",在给定的上下文中无效

Eni*_*ity 7

很简单:

this.Entity = typeof(T).Name;
Run Code Online (Sandbox Code Playgroud)