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

1

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

问题描述

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

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.

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

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14