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.
这篇关于将属性添加到另一个程序集的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将属性添加到另一个程序集的类
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01