I want to have a class like this (pseudocode):

public MyClass
{
   private bool isValid;

   [CheckValid]
   public int DoSomething()
   {
      return 1;
   }
}

Now, I want my [CheckValid] attribute to check isValid property, and if it is true, then allow DoSomething() to execute, or, if it is false, make DoSomething() return default(int) (or at least make the code inside DoSomething() inaccesible)

有帮助吗?

解决方案

That is not a feature of C#: attributes are not executed as such. There are, however, extension frameworks like PostSharp that would allow this - basically it rewrites the code at the IL level to inject functionality, typically based on attributes. But that requires additional tooling.

In C# "out of the box", your best bet would be:

public int DoSomething() {
    CheckValid(); // might throw an exception
    return 1;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top