[英]How do I get the public properties of an Object if I have the type name in a string in C#?
我有很長的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
} #>
}
}
像這樣:
foreach (PropertyInfo p in Type.GetType(typeName).GetProperties())
{
Console.WriteLine(p.Name);
}
如果您具有類型的全限定名,則可以使用Type.GetType(string)
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.