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

Joh*_*ny5 5 c# attributes

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

我在程序集FooBar中有例子:

public class Foo
{
   public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

Joã*_*elo 7

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

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

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

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
}
Run Code Online (Sandbox Code Playgroud)

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