如果我在C#中的字符串中有类型名称,如何获取Object的公共属性?

时间:2014-06-26 22:13:53

标签: c# reflection t4 asp.net-mvc-scaffolding

我在C#中有很长的对象列表,我想编写一系列"单元测试存根"通过MvcScaffolding。

我希望能够加载对象的元数据并循环访问对象的公共属性。

但是,在上下文中我不想(并且在某些情况下不能)创建对象的实际副本。

如果我只有字符串中的类型名称,C#中是否有方法可以读取对象的公共属性?

我试图在T4模板中加载属性

例如我正在尝试:

<#@ Template Language="C#" HostSpecific="True" Inherits="DynamicTransform" #>
<#@ assembly name="C:\www\myproject\Web\bin\MyCustomAssembly.dll" #>
<#@ Output Extension="cs" #>
<#@ import namespace="MyCustomAssembly" #>

[TestClass]
public class <#= Model.PluginName #>ServiceTest
{
    // Example model value from scaffolder script: <#= Model.ExampleValue #>
    // 
<# 
    Type foo = Type.GetType("MyCustomAssembly."+Model.PluginName + "Service");
    if (foo == null) {
#>
// <#= "NULL" #>
<# } else {  
        // Output one generic UnitTest per Property in the object type
   } #>

}

}

2 个答案:

答案 0 :(得分:2)

像这样:

foreach (PropertyInfo p in Type.GetType(typeName).GetProperties())
{
    Console.WriteLine(p.Name);
}

答案 1 :(得分:1)

如果您的类型为fully-qualified name,那么您可以使用Type.GetType(string)方法。