如何在运行时确定动态属性的类型

时间:2014-09-12 20:39:21

标签: c#-4.0 dynamic

我有一个简单的POCO类,其中一个公共属性被定义为动态。是否可以在运行时确定此属性的类型? 我尝试使用这样的反射来获取类型:

myObject.GetType().GetProperties();

或者这个:

System.ComponentModel.TypeDescriptor.GetProperties(myObject);

但两者都返回System.Object而不是当前类型。 在Visual Studio调试器中,我看到列为“dynamic {System.DateTime}”或“dynamic {System.Int32}”的类型,表明可以在运行时读取类型。那怎么做呢?

编辑 - 添加显示问题的示例程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynamicTypeSample
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTag datatag1 = new DataTag() { Id = Guid.NewGuid(), Name = "datatag1", Value = new DateTime(2014, 9, 12) };
            DataTag datatag2 = new DataTag() { Id = Guid.NewGuid(), Name = "datatag2", Value = (int)1234 };

            var propertyTypes1 = GetPropertyTypes(datatag1);
            var propertyTypes2 = GetPropertyTypes(datatag2);

            foreach (var p in propertyTypes1)
            {
                Console.WriteLine(p.Key + " " + p.Value.ToString());
            }

            foreach (var p in propertyTypes2)
            {
                Console.WriteLine(p.Key + " " + p.Value.ToString());
            }

            Console.ReadLine();
        }

        private static Dictionary<string, Type> GetPropertyTypes(DataTag datatag)
        {
            Dictionary<string, Type> results = new Dictionary<string, Type>();
            foreach (var pi in (typeof(DataTag)).GetProperties())
            {
                results.Add(pi.Name, pi.PropertyType);
            }
            return results;
        }

    }


    public class DataTag
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public dynamic Value { get; set; }
    }
}

输出如下:
Id Sytem.Guid
名称System.String
价值体系。对象
Id Sytem.Guid
名称System.String
价值体系。对象

我想要实现的是:
Id Sytem.Guid
名称System.String
价值体系。日期时间
Id Sytem.Guid
名称System.String
价值体系.Int32

1 个答案:

答案 0 :(得分:0)

如果我没弄错的话。你在那里做的是获取对象属性。

您可以做的是使用反射来遍历属性以获取其基本信息和数据类型。

也许你应该尝试这样的事情:

PropertyInfo[] propsobj = typeof(MyClassType).GetProperties();
foreach(PropertyInfo p in propsobj)
{
    object[] attribs = p.MyProperty;
}

希望它有所帮助。 干杯!

相关问题