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

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

我在程序集FooBar中有例子:

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

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

如果第三方工具使用标准reflection来获取类型的属性,则不能。

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

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

 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属性。

不可以。不可能从单独的程序集中向类型添加属性。

但是,您可以创建自己的包装第三方类型的类型。 由于您可以完全控制包装器类,因此可以在其中添加属性。

关于什么:

 public class Foo { public virtual string Bar } public class MyFoo : Foo { [yourcustomattribute] public overrides string Bar } 

我认为您需要的是某种适配器层,它不会让基础架构依赖性泄漏到您的域逻辑中。 也许你可以创建一个类似于其他技术的数据传输对象的适配器类。 此类存在于依赖于第三方库的集成程序集中:

 public class FooDTO { [TheirAttribute] public string Bar { get; set; } } 

然后,您可以使用AutoMapper之类的东西来减轻更改表示的痛苦。

但是,理想的解决方案是第三方库是否支持其他方式来提供有关其操作的元数据。 也许你可以问他们这个function。