c# - 知道对象的字段/属性是 "simple/primitive"类型还是其他对象?

标签 c# properties field

我得到了以下生成 DLL 的代码(示例):

public class PluginClass
{
    private string _MyString;
    public string MyString
    {
        get { return _MyString; }
        set
        {
            _MyString = value;
            RaisePropertyChanged("MyString");
        }
    }

    public int MyInt;

    public SpeedGenerator SpeedGenerator1 = new SpeedGenerator();

    public GaugeValueGenerator GaugeValueGenerator1
    {
        get;
        set;
    }

    public PluginClass()
    {
        GaugeValueGenerator1 = new GaugeValueGenerator();
    }
}

如您所见,我有 4 个字段/属性。

1 个原始字段(原始类型为 int/string/bool/etcetc...):MyInt 1 个原始属性:MyString 1 个对象字段:SpeedGenerator1 1 个对象属性:GaugeValueGenerator1

当我解析我的 DLL 时,我必须执行函数中的一些代码:WriteProperty

var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
var props = type.GetProperties();

foreach (FieldInfo field in fields)
{
    WriteProperty(field.FieldType, field.Name, XXX);
}

foreach (PropertyInfo prop in props)
{
    WriteProperty(prop.PropertyType, prop.Name, XXX);
}

我的问题是关于 XXX,它是一个 bool 值,指示我的字段/属性是否为“原始”。所以如果是对象就必须设置为false。 我摔倒了,好像我什么都试过了,但我无法解决它…… 任何帮助将不胜感激!

(我的想法是调用

var props = propertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

并考虑对于简单/原始类型它应该是空的!但是不...例如在 String 上,这会返回属性 Chars (char[]) 和 Length (int)...)

(nb : 当然我不想对字段/property.Name/FullName 进行字符串操作...类似

if ((propertyType.FullName).Contains("System."))

会非常非常糟糕……而且不准确)

最佳答案

应该这样做。

 public static bool IsPrimate(this object obj)
    {
        return new[]
        {
            typeof (Enum),
            typeof (String),
            typeof (Char),
            typeof (Guid),
            typeof (Boolean),
            typeof (Byte),
            typeof (Int16),
            typeof (Int32),
            typeof (Int64),
            typeof (Single),
            typeof (Double),
            typeof (Decimal),
            typeof (SByte),
            typeof (UInt16),
            typeof (UInt32),
            typeof (UInt64),
            typeof (DateTime),
            typeof (DateTimeOffset),
            typeof (TimeSpan),
        }.Any(oo => oo.IsInstanceOfType(obj));
    }

关于c# - 知道对象的字段/属性是 "simple/primitive"类型还是其他对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8563220/

相关文章:

C#.Net : Why is my Process. Start() 挂起?

c# - Windows 无法在本地计算机上启动服务错误 5 访问被拒绝

C#字符串 "likeness"对比测试

c# - 使用{设置;得到;}而不是{得到;放;}

json - 如何在golang中获取结构的json字段名称?

java - 如何使用来自数据库的值验证 Tapestry 的表单字段?

c# - 接口(interface)作为c#中方法的参数

c# - 属性永远不会为 null c#

php - Woocommerce 中的自定义购物车商品重量

Java:为什么静态字段彼此都是 "independent"?