将属性添加到另一个程序集的类

Add an attribute to another assembly#39;s class(将属性添加到另一个程序集的类)

本文介绍了将属性添加到另一个程序集的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能扩展在另一个程序集中定义的类型,以在其属性之一上添加属性?

Is it somehow possible to extend a type, wich is defined in another assembly, to add an attribute on one of its properties?

我在装配 FooBar 中的示例:

Exemple I have in assembly FooBar:

public class Foo
{
   public string Bar { get; set; }
}

但在我的 UI 程序集中,我想将此类型传递给第三方工具,并且为了让该第三方工具正常工作,我需要 Bar 属性具有特定属性.这个属性是在第三方程序集中定义的,我不想在我的 FooBar 程序集中引用这个程序集,因为 FooBar 包含我的域并且这是一个 UI 工具.

But in my UI assembly, I want to pass this type to a third party tool, and for this third party tool to work correctly I need the Bar property to have a specific attribute. This attribute is defined in the third party assembly, and I don't want a reference to this assembly in my FooBar assembly, since FooBar contains my domain an this is a UI tool.

推荐答案

你不能,如果第三方工具使用标准反射来获取你的类型的属性.

You can't, if the thirdy-party tool uses standard reflection to get the attributes for your type.

您可以,如果第三方工具使用 TypeDescriptor API 来获取您的类型的属性.

You can, if the third-party tool uses the TypeDescriptor API to get the attributes for your type.

类型描述符案例的示例代码:

Sample code for the type descriptor case:

public class Foo
{
    public string Bar { get; set; }
}

class FooMetadata
{
    [Display(Name = "Bar")]
    public string Bar { get; set; }
}

static void Main(string[] args)
{
    PropertyDescriptorCollection properties;

    AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider;

    properties = TypeDescriptor.GetProperties(typeof(Foo));
    Console.WriteLine(properties[0].Attributes.Count); // Prints X

    typeDescriptionProvider = new AssociatedMetadataTypeTypeDescriptionProvider(
        typeof(Foo),
        typeof(FooMetadata));

    TypeDescriptor.AddProviderTransparent(typeDescriptionProvider, typeof(Foo));

    properties = TypeDescriptor.GetProperties(typeof(Foo));
    Console.WriteLine(properties[0].Attributes.Count); // Prints X+1
}

如果您运行此代码,您将看到最后一个控制台写入打印加上一个属性,因为现在还考虑了 Display 属性.

If you run this code you'll see that last console write prints plus one attribute because the Display attribute is now also being considered.

这篇关于将属性添加到另一个程序集的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将属性添加到另一个程序集的类

基础教程推荐