简体   繁体   中英

C# access T of generic class in its own method

Im just starting with generics and was wondering how I can access T of the class in a class method? Lets take some code to explain better what I want to do:

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;
    }

}

Thank you very much for all helpful and well meant answers!

UPDATE: Errormessage from Visual Studio

"T" is "type Parameter" and not valid in given context

就这么简单:

this.Entity = typeof(T).Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM