【问题标题】:How to determine type of a dynamic property at runtime如何在运行时确定动态属性的类型
【发布时间】:2014-09-13 05:54:16
【问题描述】:

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

myObject.GetType().GetProperties();

或者这个:

System.ComponentModel.TypeDescriptor.GetProperties(myObject);

但两者都返回 System.Object 而不是当前类型。 在 Visual Studio 调试器中,我看到列为“动态 {System.DateTime}”或“动态 {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; }
    }
}

输出如下:
标识系统.Guid
名称 System.String
值 System.Object
标识系统.Guid
名称 System.String
值 System.Object

我想要实现的是:
标识系统.Guid
名称 System.String
值 System.DateTime
标识系统.Guid
名称 System.String
值 System.Int32

【问题讨论】:

    标签: c#-4.0 dynamic


    【解决方案1】:

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

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

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

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

    希望对您有所帮助。 干杯!

    【讨论】:

    • 对不起,没有。这将返回 System.Object。我添加了一个完整的示例程序来演示。
    • 哦!我明白了,所以也许这篇文章可能会对你有所帮助:stackoverflow.com/questions/7362532/…
    • 不,我看不出这有什么帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 2019-06-02
    相关资源
    最近更新 更多