JTinkers
JTinkers

Reputation: 1789

Storing classes with generic types in a single array

I have a class Validator<T> and a multitude of other classes that inherit from it like: TagValidator : Validator<Tag>.

Let's say I want to make a single ModelValidator class that stores all the classes that inherit from Validator<T> and runs a specific one when I do ModelValidator.Validate<T>(T model)

Is there a way to store classes with a generic type in a single array or perhaps a dictionary?

Upvotes: 0

Views: 61

Answers (1)

Enigmativity
Enigmativity

Reputation: 117029

I feel like this is not as hard as the comments make out.

Does this kind of thing work?

void Main()
{
    var mv = new ModelValidator();
    mv.AddValidator(new TagValidator());
    mv.AddValidator(new FooValidator());
    
    var tag = new Tag();
    
    mv.Validate(tag);
}

public class ModelValidator
{
    private List<object> _validators = new List<object>();
    
    public void AddValidator<T>(Validator<T> validator)
    {
        _validators.Add(validator); 
    }
    
    public void Validate<T>(T model)
    {
        foreach (Validator<T> validator in _validators.OfType<Validator<T>>())
        {
            validator.Validate(model);
        }
    }
}

public abstract class Validator<T>
{
    public virtual void Validate(T model) { }
}

public class TagValidator : Validator<Tag> { }
public class FooValidator : Validator<Foo> { }

public class Tag { }
public class Foo { }

Upvotes: 2

Related Questions