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.
这篇关于将属性添加到另一个程序集的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将属性添加到另一个程序集的类
基础教程推荐
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 从 C# 控制相机设备 2022-01-01
