gpt4 book ai didi

c# - 获取要在自定义属性中使用的属性值

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:48 24 4
gpt4 key购买 nike

我一直在寻找如何从自定义属性代码中获取属性值的示例。

示例仅供说明:我们有一个简单的书籍类,只有一个名称属性。 name 属性有一个自定义属性:

public class Book
{
[CustomAttribute1]
property Name { get; set; }
}

在自定义属性的代码中,我想获取装饰属性的属性值:

public class CustomAttribute1: Attribute
{
public CustomAttribute1()
{
//I would like to be able to get the book's name value here to print to the console:
// Thoughts?
Console.WriteLine(this.Value)
}
}

当然,“this.Value”是行不通的。有什么想法吗?

最佳答案

好的,我明白了。这仅适用于 .Net 4.5 及更高版本。

在 System.Runtime.CompilerServices 库中,有一个 CallerMemberNameAttribute 类可用。要获取调用类的名称,有一个 CallerFilePathAttribute 类,它返回调用类的完整路径,供以后与 Reflection 一起使用。两者的用法如下:

public class CustomAttribute1: Attribute
{
public CustomAttribute1([CallerMemberName] string propertyName = null, [CallerFilePath] string filePath = null)
{
//Returns "Name"
Console.WriteLine(propertyName);

//Returns full path of the calling class
Console.WriteLine(filePath);
}
}

希望这对您的工作有所帮助。

关于c# - 获取要在自定义属性中使用的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28710689/

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