A method that converts a string to an enumerated type

  • 2020-06-07 05:11:22
  • OfStack

There are two types of user User registration: Super and Common


public eumn RegistrationType
{
    Super;
    Common;
}
public User
{
    RegistrtionType type;
    ......
}

Consider the case where, through some service, the client gets the name of the class passed in from the server and the values of the various attributes, including User, but also other classes Product, Shop, etc., which are strings of course. On the client side, we need to assemble this information into an instance of a class. We can use if to determine the class name passed, and new1 instance comes out, determines the attributes and assigns values. But we can't tell with if if we're not sure which classes are coming. We can do this by using reflection. Once we get the class name, we can reflect an instance of the class and assign values to the properties.
For example, if the server passes "User Super", that is, this is an User class whose RegistrtionType is Super. How do I turn this Super string into an enumeration? You can use the following method to say that an instance user is reflected, then its properties are obtained, and then assigned.
prop.SetValue(user, TypeDescriptor.GetConverter(prop.PropertyType).ConvertFromInvariantString("Super"), null);


Related articles: