如何从字符串创建类型并在运行时解析

时间:2016-02-09 16:29:11

标签: c# .net

我有一个输入字符串,可以是int,string,float或任何数据类型。

现在我想做一些事情:

string stringType= "Int";  
Type dataType = Type.GetType(stringType);

string someValue = 20;

int newValue = (dataType)someValue ;

修改

我将收到type和value作为字符串,需要将它们转换为运行时间。

 public void StoreWorkData(List<TypeAndvalue> workDataPropertyDetails)
        {
            foreach (var property in workDataPropertyDetails)
            {
                string stringType = property.dataType;
                //Want to create the type in run time     
                Type dataType = Type.GetType(stringType);

                //Assign the value to type created above    
                dataType newValue = (dataType)property.Value;
            }
        }

3 个答案:

答案 0 :(得分:3)

好的,首先我们创建一个方法来将字符串解析为object:

static object Parse(string typeName, string value)
{
    var type = Type.GetType(typeName);
    var converter = TypeDescriptor.GetConverter(type);

    if (converter.CanConvertFrom(typeof(string)))
    {
        return converter.ConvertFromInvariantString(value);
    }

    return null;
}

在您发布的方法中,您可以调用它:

public void StoreWorkData(List<TypeAndvalue> workDataPropertyDetails)
{
    foreach (var property in workDataPropertyDetails)
    {
        dynamic newValue = Parse(property.dataType, property.Value);

        SomeMethod(newValue);
    }
}

您可以使用不同的SomeMethod方法使用不同的参数类型:

void SomeMethod(int value);
void SomeMethod(double value);
...

动态类型可以调用正确的方法(如果存在)。 有关详细信息,请查看this

答案 1 :(得分:2)

Type.GetTypeused correctly会为您提供一个Type实例,该实例本身可用于通过类似Activator.CreateInstance的内容创建该类型的实例。

string desiredTypeName = /* get the type name from the user, file, whatever */
Type desiredType = Type.GetType(desiredTypeName);
object instance = Activator.CreateInstance(desiredType);

如果desiredTypeName是&#34; System.String&#34;,那么instance将是string。如果是&#34; YourNamespace.YourType&#34;那么instance将是YourType。等等。

如果您需要使用参数there are overloads of CreateInstance that allow you to specify constructor parameters构建实例。

如果构造函数参数的值也作为字符串提供给您,则可以使用Type实例上的desiredType对象的方法get the available constructors并确定其所需参数键入并将字符串解析为这些类型。

请注意,此方法将限制您在编译时使用System.Object的{​​{1}}接口;当然,您将无法编写自然地将实例作为运行时类型访问的代码,因为直到运行时才知道该类型。你可以根据需要打开类型名称和向下转发instance,但那时你做了很多工作(所有那些instance垃圾),实际上什么都没有。

另请注意,Activator不是最快方式来创建在运行时确定的类型实例;它只是最简单的。

答案 2 :(得分:1)

Activator.CreateInstance可用于在运行时创建Type实例

string stringType= "MyType";  
Type dataType = Type.GetType(stringType);
dynammic instance = Activator.CreateInstance(dataType);

要支持从字符串转换,您必须在类型

中实现以下方法
public static explicit operator MyType(string s)
{
   // put logic to convert string value to your type
    return new MyType
    {
        value = s;
    };
}