extending Convert.ChangeType to produce user-defined types on request

后端 未结 4 1975
孤城傲影
孤城傲影 2021-01-01 11:52

Given the class:

public class Foo
{
    public string Name { get; set; }
}

Is it possible to have a Foo instance created from a string thro

4条回答
  •  耶瑟儿~
    2021-01-01 12:30

    object value1 = "one";

    Foo value2 = (Foo) System.Convert.ChangeType(value, typeof(Foo));

    Edit:


    Ok then, if you are trying to create type of Foo from string, you could use reflection:

    String controlToCreate = "Foo";
    Type typeofControl = Type.GetType(controlToCreate,true);
    

提交回复
热议问题