【问题标题】:Get Properties of baseclass and specific inherited class获取基类和特定继承类的属性
【发布时间】:2015-11-17 08:30:45
【问题描述】:

我有一个基类 CrmObject 和一些继承它的类(Aufgabe、Kontakt、...)。我只有一个子类的字符串值,我想在一个语句中同时获取 CrmObject 的属性和特定的子类。

我会像这样得到子类的属性:

var propertyInfos = typeof(CrmObject).Assembly.GetType("Aufgabe").GetProperties().Where(p => Attribute.IsDefined(p, typeof(ImportParameter)));

但我也想获得 CrmObject 的属性。可能在同一个语句中。

[更新] 这应该是它。我稍后会测试它。谢谢你们。 :)

var propertyInfos = typeof(CrmObject).Assembly.GetType("DAKCrmImport.Core." +crmType).G‌​etProperties().Where(p => Attribute.IsDefined(p, typeof(ImportParameter)));

奇怪的是,您不需要 bindingflag 参数来展平层次结构。显然这是默认值?嗯..随便。它有效:)

【问题讨论】:

  • 你需要BindingFlags.FlattenHierarchy
  • 您的代码应该可以正常工作。尝试删除 where 子句。
  • 哦,谢谢。所以声明看起来像这样:var propertyInfos = typeof(DAKCrmImport.Core.Entities.CrmData.CrmObject).Assembly.GetType(crmType).GetProperties(BindingFlags.FlattenHierarchy).Where(p => Attribute.IsDefined(p, typeof(ImportParameter)));
  • GetType 期望类型的全名。

标签: c# reflection


【解决方案1】:

对我来说很好。

public class CrmObject
{
    [ImportParameter]
    public string Name { get; set; }
}

public class Aufgabe : CrmObject
{
    [ImportParameter]
    public int Id { get; set; }
}

public class ImportParameterAttribute : Attribute
{

}

public class InheritenceProgram
{
    public static void Main()
    {
        var propertyInfos = typeof(CrmObject).Assembly.GetType("Aufgabe").GetProperties().Where(p => Attribute.IsDefined(p, typeof(ImportParameterAttribute)));
        var list = propertyInfos.ToList();
    }
}

【讨论】:

  • 嗯 .. 但我也想要 CrmObject 的属性。我很确定我不会以这种方式得到它们。我只会得到“Aufgabe”的属性。
  • GetType 除外FullName 类型。
  • 您将获得所有用属性 ImportParameter 标记的属性。在我的示例中,您应该获得 Id 和 Name。
  • 正如 Amit Kumar Ghosh 所说,您需要将 FullName 与 GetType 一起使用。我的示例仅在您不使用命名空间时才有效。
【解决方案2】:

正如马克所说,您需要指定BindingFlags.FlattenHierarchy
但是当你指定BindingFlags 时,你需要准确地指定你想要的。这意味着您还必须指定BindingFlags.Instance 以获取实例成员,并指定BindingFlags.Public 以包含公共成员

所以命令看起来像这样:

var propertyInfos = typeof(CrmObject).Assembly.GetType(crmType).G‌​etProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public).Where(p => Attribute.IsDefined(p, typeof(ImportParameter)));

您可以在great SO answerType.GetProperties 的文档中了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    相关资源
    最近更新 更多