문제

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