从接口方法和类方法获取属性
当方法重载时,从类方法和接口方法获取属性值的最佳方法是什么?
例如,我想知道在下面的示例中,带有一个参数的 Get 方法具有两个属性,值为 5 和“any”,而另一种方法具有值为 7 和“private”的属性。
public class ScopeAttribute : System.Attribute
{
public string Allowed { get; set; }
}
public class SizeAttribute : System.Attribute
{
public int Max { get; set; }
}
public interface Interface1
{
[SizeAttribute( Max = 5 )]
string Get( string name );
[SizeAttribute( Max = 7 )]
string Get( string name, string area );
}
public class Class1 : Interface1
{
[ScopeAttribute( Allowed = "any" )]
public string Get( string name )
{
return string.Empty;
}
[ScopeAttribute( Allowed = "private" )]
public string Get( string name, string area )
{
return string.Empty;
}
}
Whats the best approach for getting the attribute values from a classes methods and from the interface methods when the methods are overloaded?
For example I would want to know that in the following example the Get method with one parameter has the two attributes and the values are 5 and "any" while the other method has attributes with values 7 and "private".
public class ScopeAttribute : System.Attribute
{
public string Allowed { get; set; }
}
public class SizeAttribute : System.Attribute
{
public int Max { get; set; }
}
public interface Interface1
{
[SizeAttribute( Max = 5 )]
string Get( string name );
[SizeAttribute( Max = 7 )]
string Get( string name, string area );
}
public class Class1 : Interface1
{
[ScopeAttribute( Allowed = "any" )]
public string Get( string name )
{
return string.Empty;
}
[ScopeAttribute( Allowed = "private" )]
public string Get( string name, string area )
{
return string.Empty;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现的唯一方法是检查类实现了哪些接口,并检查这些接口上的属性(如果存在)的属性:
您可能可以同样轻松地将其采用到方法中。
注意:整体方法已经过测试,但代码本身是临时的,可能无法编译。
The only way I found was to check what interfaces the class implements and check attributes of the properties (if any exist) on those interfaces:
You can probably adopt it to methods equally easy.
Note: overall approach is tested but the code itself is ad-hoc and may not compile.
您可以使用 TypeDescriptor API
You can use TypeDescriptor API
您应该使用反射来获取自定义属性值
,使用 < code>MemberInfo.GetCustomAttributes 方法 返回附加到您的成员的自定义属性
,这里是一个教程 http://msdn.microsoft.com/en-us /library/aa288454(v=VS.71).aspx
编辑:要从界面获取属性,请查看 此处
You should use reflection to get the custom attributes values
use
MemberInfo.GetCustomAttributes
Method to return the custom attributes attached to your memberhere is a tutorial http://msdn.microsoft.com/en-us/library/aa288454(v=VS.71).aspx
EDIT: for get attributes from interface look at here