一个属性添加到其他程序集的类 [英] Add an attribute to another assembly's class

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

问题描述

是它在某种程度上可以延长一个类型,至极在另一个程序集中定义,在其属性之一添加属性?

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组件,我想通过这种类型的第三方工具,并为此第三方工具才能正常工作,我需要酒吧属性有特定属性。此属性是第三方组件定义的,我不希望本次大会在我FooBar的程序集的引用,因为FooBar的包含我的域名一个,这是一个用户界面工具。

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.

推荐答案

您不能,如果thirdy第三方工具使用标准的反射得到的属性你的类型。

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.

样code的类型说明符的情况下:

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
}

如果您运行此code,你会看到最后的控制台写入打印加一个属性,因为显示属性现在也正在考虑中。

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆