gpt4 book ai didi

c# - 如何获取属性值

转载 作者:太空狗 更新时间:2023-10-29 20:22:21 24 4
gpt4 key购买 nike

我有这个代码:

[MyAttribute(CustomAttribute="Value")]
class MyClass
{
// some code
}


Main()
{
MyClass a = new MyClass();
}

如何获取实例a的CustomAttribute的值?

最佳答案

沿着:

MyAttribute [] myAttributes 
= (MyAttribute [])a.GetType().GetCustomAttributes(typeof(MyAttribute),true);

无法理解“不使用 foreach”是什么意思,只是 GetCustomAttributes 总是返回它们的数组(以说明具有多个属性)。如果您知道只能有一个,则只使用第一个。

MyAttribute theAttrib = myAttributes[0];
Console.WriteLine(theAttrib.CustomAttribute);

关于c# - 如何获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3388412/

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