简体   繁体   中英

Generic method set value of base class property

I'm writing a generic method to put set values on the base class

public class StageOne: DefaultValues
{
    //StageOne properties
}

public class DefaultValues
{
    public string status { get; set; }
    public string message { get; set; }
}

private T SetValue<T>() where T : DefaultValues
{
    T.message = "Good Job";
    T.status = "Done";
    return default(T);
}

I get an error on T.message and T.status ; T is type parameter, which is not valid in the given context

I have already Googled it and I can't find my answer - please help.

Thanks.

If you want to set properties of the generic type, then you need an instance of the type. To get an instance we either need to have the caller pass one in as an argument, or create a new one (and if we choose this option, we need to include the new() constraint as well):

First option - have the caller pass in an instance of the type (no need for a return value in this case since the caller already has a reference to the instance we're changing):

private void SetValue<T>(T input) where T : DefaultValues
{
    input.message = "Good Job";
    input.status = "Done";
}

Second option - create a new instance of the type inside the method (note the added generic constraint, new() ):

private T SetValue<T>() where T : DefaultValues, new()
{
    T result = new T();
    result.message = "Good Job";
    result.status = "Done";
    return result;
}

Which could be simplified to:

private static T SetValue<T>() where T : DefaultValues, new()
{
    return new T {message = "Good Job", status = "Done"};
}

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