2

I'm getting a compile-time error that my method call has some invalid arguments.

public abstract class EntityBase
{
    public virtual List<ValidationResult> Validate<T>()
    {
        // This line causes the error:
        var validationResults = this.ValidateEntity<T>(this, true).ToList();
    }

    protected IEnumerable<ValidationResult> ValidateEntity<T>(T entity, bool ignoreNullViolations)
    {
        // Code here
    }
}

The class is abstract. That should be ok. I tried specifying the type of T in the method signature but that didn't help. Why won't this compile? I can't pass this to a method expecting a T parameter?

EDIT -- Possible solution:

public virtual List<ValidationResult> Validate<T>() where T : class
{
    var validationResults = this.ValidateEntity<T>(this as T, true).ToList();
}

EDIT 2

Since T should only be a subclass, I think the class signature should change to be generic so that forces the subclass to set it. Then passing this wouldn't be such a hack.

4

1 回答 1

5

Your ValidateEntity method is declared such that the first parameter is of type T.

Now look how you're calling it:

var validationResults = this.ValidateEntity<T>(this, true).ToList();

You're trying to implicitly convert this to T - what makes you think that should work?

Suppose I called:

foo.Validate<string>();

That would try to pass this to a method effectively expecting a string - that's clearly not going to work, as this is a reference to an instance of some concrete subclass of EntityBase - not a reference to a string.

于 2012-10-29T18:14:20.350 回答