Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在c#中属性类的构造函数中,如何判断正在处理哪个属性目标?_C#_Custom Attributes - Fatal编程技术网

在c#中属性类的构造函数中,如何判断正在处理哪个属性目标?

在c#中属性类的构造函数中,如何判断正在处理哪个属性目标?,c#,custom-attributes,C#,Custom Attributes,如果您具有以下属性类: [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)] public class MyValidationAttribute : Attribute { public string Message { get; set; } public MyValidationAttribute() { // If this is decorating a pro

如果您具有以下属性类:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
public class MyValidationAttribute : Attribute
{
    public string Message { get; set; }

    public MyValidationAttribute()
    {
        // If this is decorating a property, do this
        if (this.DecoratesProperty)  // Of course this is totally made up
        {
            Message = "This is decorating a property";
        }
        else
        {
            Message = "This is decorating a class";
        }
    }
    ...
}
我只是编了一个(非工作)的方式来询问这个装饰是否在一个属性上(相对于一个类)。但是有没有一种方法是真实的呢


当然要提前感谢。

在声明属性时,您能通过构造函数参数告诉它吗

e、 g


在声明属性时,您能通过构造函数参数告诉它吗

e、 g


你的用例是什么?由于属性本身并不意味着什么,因此必须有代码来查找它,并且这段代码确实知道它是否是类/方法/参数……用例是一个相当复杂的系统,它有一个现有的基础结构来处理WCF服务器上WCF服务请求结构的验证。验证当前通过附加到这些请求结构中的各种属性的属性来完成。有许多验证是以这种方式实现的,包括一个验证,其任务是在WCF响应中包含一条消息,该消息表示此属性将被弃用。我的目标是使用相同的基础设施,以便能够使用属性将请求结构本身修饰为不推荐的结构。我仍然不明白为什么需要属性必须知道其目标。。。在您的示例中,您可以
GetMessage(target)
而不是属性(因为选择属性的代码必须知道它是类型还是属性,至少要能够找到属性)…您的用例是什么?由于属性本身并不意味着什么,因此必须有代码来查找它,并且这段代码确实知道它是否是类/方法/参数……用例是一个相当复杂的系统,它有一个现有的基础结构来处理WCF服务器上WCF服务请求结构的验证。验证当前通过附加到这些请求结构中的各种属性的属性来完成。有许多验证是以这种方式实现的,包括一个验证,其任务是在WCF响应中包含一条消息,该消息表示此属性将被弃用。我的目标是使用相同的基础设施,以便能够使用属性将请求结构本身修饰为不推荐的结构。我仍然不明白为什么需要属性必须知道其目标。。。在您的示例中,您可以
GetMessage(target)
而不是属性(因为选择属性的代码必须知道它是类型还是属性,至少要能够找到属性)…这当然是可能的,尽管对于我的用例来说可能有点不雅(参见上面的注释)。这可能是必要的,但我希望有一个更优雅的解决方案。这当然是可能的,尽管对我的用例来说可能有点不雅观(见上面的评论)。这可能是必要的,但我希望有一个更优雅的解决方案。
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
public class TestAttribute : Attribute
{
    public TestAttribute(Type target)
    {
        if (target == typeof(object))
        {

        }
        else if (target == typeof(PropertyInfo))
        {

        }
    }
}

[TestAttribute(typeof(object))]
class SomeClass
{
    [TestAttribute(typeof(PropertyInfo))]
    public string SomeProperty { get; set; }
}