通过在运行时传入一个字符串来获取底层对象C#

时间:2013-09-26 11:44:06

标签: c# generics

所以我有一个创建一个新对象的方法:

public class Objects<TObject>
{
    public NodeReference<TObject> CreateObject<TObject>(TObject objectType) 
                where TObject: class, new()
            {
                NodeReference<TObject> nodeReference = 0;

                return nodeReference;
            }
}

现在我有其他对象类定义其他对象类型,如Car。

public class Car
{
    public int NumberOfDoors {get; set;}
    public int NumberOfWheels {get; set;}
}

现在假设我传递了一个字符串如何在运行时将此字符串转换为其类型?

var carObjectReference = CreateObject<//string converted to identify object car dynamically>(//new Car { });

1 个答案:

答案 0 :(得分:1)

public object ReturnValue(string operationName, object returnValue)
{
    Type t = returnValue.GetType();
    return Activator.CreateInstance(t);
}