سؤال

I have an abstract dataprovider, with lots of methods.

In the implementation, every method needs to do some check, before continuing with the rest of the method. This check is always the same.

So now in every method, I do this:

public override string Method1 {
    if(myCheck()) throw new Exception(...);
    ...Rest of my method1...
}
public override string Method2 {
    if(myCheck()) throw new Exception(...);
    ...Rest of my method2...
}
public override string Method3 {
    if(myCheck()) throw new Exception(...);
    ...Rest of my method3...
}

you get the point..

Is there an easier / better / shorter way to do this?

هل كانت مفيدة؟

المحلول

There is no built in feature for this in C#. You can do it in PostSharp though.

public sealed class RequiresCheckAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionEventArgs e)
    {
        // Do check here.
    }
}

If you want to do this in plain C#, a minor improvement that can make your life easier is refactoring the code into a separate method:

public void throwIfCheckFails() {
    if(myCheck()) throw new Exception(...);
}

public override string Method1 {
    throwIfCheckFails();
    // ...Rest of my method1...
}

This doesn't force every method to perform the check - it just makes it easier.

نصائح أخرى

You could just mplement a base class in the following way:

public virtual string MethodCalledByMethod1 {
}

public virtual string MethodCalledByMethod2 {
}

public virtual string MethodCalledByMethod3 {
}

public string Method1 {
    if(myCheck()) throw new Exception(...);
    return MethodCalledByMethod1();
}
public string Method2 {
    if(myCheck()) throw new Exception(...);
    return MethodCalledByMethod2();
}
public string Method3 {
    if(myCheck()) throw new Exception(...);
    return MethodCalledByMethod3();
}

And then in your child classes

public override string MethodCalledByMethod1 {
    ...Rest of my method1...
}

public override string MethodCalledByMethod2 {
    ...Rest of my method1...
}

public override string MethodCalledByMethod3 {
    ...Rest of my method1...
}

Basically you override methods 1 through 3 which are called by the base class implementation. The base class implementation contains the mycheck() and so you only have to worry about writing this once (ie in the base class implementation).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top