简体   繁体   English

在C#中使用反射将一类的数据类型转换为另一类

[英]Data type of one class to other class using reflection in C#

I have a class 我有一堂课

namespace MyNamespace1
{
    class MyClass
    {
        public string MyName { get; set; }
        public int? MaxHeaderLength { get; set; }
        public System.Collections.Generic.List<MyClass.ViewModel> Preferences { get; set; }
    }
}

namespace MyNamespace2
{
    internal class myClass1
    {
        public static void Main(string[] args)
        {
            var properties = loading assembly of the MyClass of MyNamespace1
            var prop = properties.GetProperties();
            foreach (var propertyInfo in prop)
            {
                Console.WriteLine(propertyInfo.PropertyType.FullName);

            }
        }
    }
}

When I want to read the property at the runtime using reflection 当我想在运行时使用反射读取属性时

I am getting types as 我正在获取类型

System.String, System.String,

System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.Nullable`1 [[System.Int32,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]],

System.Collections.Generic.List`1[[System.Web.Mvc.SelectListItem, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]), System.Collections.Generic.List`1 [[System.Web.Mvc.SelectListItem,System.Web.Mvc,Version = 3.0.0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35]]),

But I want to retrieve as 但我想检索为

string,

int?,

System.Collections.Generic.List<MyClass.ViewModel>

Can anybody please provide me the solution. 谁能给我解决方案。

string , int? stringint? and List<MyClass.ViewModel> are all C# constructs. List<MyClass.ViewModel>都是C#构造。 They're not in .NET itself. 它们不在.NET本身中。

So you simply have to build a lookup table or a giant switch to convert the type names to .NET keywords. 因此,您只需要构建一个查找表或一个巨大的switch即可将类型名称转换为.NET关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM