获取类中每个值的属性值类型

本文关键字:类型 属性 获取 | 更新日期: 2024-09-08 08:56:41

如何获取类中每个属性的属性值类型?

this.GetType().GetProperties().ToList().ForEach(p => {
    switch(typeof(p.GetValue(this, null))) {
        case float:
            ...
            break;
        case string:
            ...
            break;
    }
});

这会产生错误Cannot resolve symbol p

解决方案:我最终选择了LINQ to SQL。只是更干净、更容易处理:)。感谢Jon

获取类中每个值的属性值类型

我不认为这是一个问题-我得到了:

Test.cs(12,29): error CS1026: ) expected
Test.cs(12,42): error CS1514: { expected
Test.cs(12,42): error CS1525: Invalid expression term ')'
Test.cs(12,44): error CS1002: ; expected
Test.cs(13,9): error CS1525: Invalid expression term 'case'
Test.cs(13,19): error CS1001: Identifier expected
Test.cs(13,19): error CS1525: Invalid expression term ':'
Test.cs(13,20): error CS1002: ; expected
Test.cs(15,9): error CS1525: Invalid expression term 'case'
Test.cs(15,20): error CS1001: Identifier expected
Test.cs(15,20): error CS1525: Invalid expression term ':'
Test.cs(15,21): error CS1002: ; expected

无法打开类型。一般来说,像这样使用ForEach是可以的。

样本代码:

using System;
using System.Linq;
class Test
{
    public string Foo { get; set; }    
    public int Bar { get; set; }
    public void DumpProperties()
    {
        this.GetType().GetProperties().ToList()
            .ForEach(p => Console.WriteLine("{0}: {1}", p.Name,
                                            p.GetValue(this, null)));
    }
    static void Main()
    {
        new Test { Foo = "Hi", Bar = 20 }.DumpProperties();
    }
}

现在无可否认,我通常不会在这里使用ForEach——我只会使用foreach循环:

foreach (var property in GetType().GetProperties())
{
    // Use property
}

就我个人而言,我认为这更干净、更容易阅读、更容易调试。

  1. 不能在Type上使用switch,因为case中没有常量值
  2. 如果您仍然需要switch,并且正在使用一组众所周知的类型(即系统类型),则可以使用返回enump.PropertyType.GetTypeCode()