Вопрос

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