gpt4 book ai didi

c# - 快速访问在 C# 中包含属性的类型/方法/...

转载 作者:太空狗 更新时间:2023-10-29 19:43:24 26 4
gpt4 key购买 nike

我在这里创建了一个名为 AAtribute 的自定义属性,例如一个名为 B 的类,其中一个或多个方法使用该属性。是否可以获取持有属性(在本例中为 BMethod1)的方法的 MethodInfo 作为(其中之一)它的属性,而无需遍历整个程序集并查看其属性的所有已定义方法?它们是其他 AttributeTargets(参数/类型/属性/...)的模拟方式吗?我不想要一个包含使用该类型属性的所有方法的数组,而只想要具有此 Attirbute 对象的方法。我想用它来对方法施加额外的约束(返回类型、参数、名称、其他属性用法……)。

[AttributeUsage(AttributeTargets.Method)]
public class AAtribute : Attribute {

//some fields and properties

public AAtribute () {//perhaps with some parameters
//some operations
MethodInfo mi;//acces to the MethodInfo with this Attribute
//as an Attribute (the question)
//some operations with the MethodInfo
}

//some methods

}

public class B {

//some fields, properties and constructors

[A]
public void BMethod1 () {
//some operations
}

//other methods

}

最佳答案

如果我对您的问题的理解正确,您希望在属性代码中获取应用该属性的对象(在本例中为方法)。
我很确定没有直接的方法可以做到这一点——属性不知道它所附加的对象,这种关联是相反的。

我能建议您的最佳解决方法如下:

using System;
using System.Reflection;

namespace test {

[AttributeUsage(AttributeTargets.Method)]
public class AAttribute : Attribute {
public AAttribute(Type type,string method) {
MethodInfo mi = type.GetMethod(method);
}
}

public class B {
[A(typeof(B),"BMethod1")]
public void BMethod1() {
}
}
}

注意
你想通过访问属性构造函数中的 MethodInfo 来实现什么?也许有另一种方法可以实现您的目标...

编辑

作为另一种可能的解决方案,您可以在执行检查的属性中提供静态方法 - 但这涉及迭代 MethodInfos。

using System;
using System.Reflection;
namespace test {

[AttributeUsage(AttributeTargets.Method)]
public class AAttribute : Attribute {
public static void CheckType<T>() {
foreach (MethodInfo mi in typeof(T).GetMethods()) {
AAttribute[] attributes = (AAttribute[])mi.GetCustomAttributes(typeof(AAttribute), false);
if (0 != attributes.Length) {
// do your checks here
}
}
}
}

public class B {
[A]
public void BMethod1() {
}
[A]
public int BMethod2() {
return 0;
}
}

public static class Program {
public static void Main() {
AAttribute.CheckType<B>();
}
}
}

关于c# - 快速访问在 C# 中包含属性的类型/方法/...,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1346010/

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