gpt4 book ai didi

c# - 如何在 C# 中创建自定义属性

转载 作者:IT王子 更新时间:2023-10-29 03:34:46 30 4
gpt4 key购买 nike

谁能用代码向我解释一个非常基本的自定义属性示例?

最佳答案

您首先编写一个派生自 Attribute 的类:

public class MyCustomAttribute: Attribute
{
public string SomeProperty { get; set; }
}

然后你可以用这个属性装饰任何东西(类、方法、属性......):

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

最后您将使用反射来获取它:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
var myAttribute = customAttributes[0];
string value = myAttribute.SomeProperty;
// TODO: Do something with the value
}

您可以使用 AttributeUsage 限制可以应用此自定义属性的目标类型属性:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

关于属性的重要事项:

  • 属性是元数据。
  • 它们在编译时 被嵌入到程序集中,这对您如何设置它们的属性有非常重要的影响。只接受常量(在编译时已知)值
  • 使自定义属性有意义和使用的唯一方法是使用 Reflection .因此,如果您不在运行时使用反射来获取它们并使用自定义属性装饰某些东西,就不会发生太多事情。
  • 属性的创建时间是不确定的。它们由 CLR 实例化,您绝对无法控制它。

关于c# - 如何在 C# 中创建自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4879521/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com