英文:
Better way to declare generic parameters on class
问题
I'm writing a FluentValidation custom validator to validate that two read-only collections have the same number of elements.
I'm using VS2022 and FluentValidation v11.5.2.
I currently have the following:
public class CollectionSizesMatchValidator<T, TProperty, TElement> : PropertyValidator<T, TProperty>
where TProperty : IReadOnlyCollection<TElement>
But I'm getting a CA1005 message: Avoid excessive parameters on generic types.
I thought this might be a better solution, but it doesn't compile:
public class CollectionSizesMatchValidator<T, IReadOnlyCollection<TElement>> : PropertyValidator<T, IReadOnlyCollection<TElement>>
I don't like the warning generated by the compiler, so I'd like to reduce the number of generic types. I thought I could use ICollection, but IReadOnlyCollection
When I use the validator, I have to supply all the types.
Is there a better solution than the one I currently have?
英文:
I'm writing a FluentValidation custom validator to validate that two read only collections have the same number of elements.
I'm using VS2022 and FluentValidation v11.5.2.
I current have the following:
public class CollectionSizesMatchValidator<T, TProperty, TElement> : PropertyValidator<T, TProperty>
where TProperty : IReadOnlyCollection<TElement>
but I'm getting a CA1005 message: Avoid excessive parameters on generic types.
I thought this might be a better solution but it doesn't compile
public class CollectionSizesMatchValidator<T, IReadOnlyCollection<TElement>> : PropertyValidator<T, IReadOnlyCollection<TElement>>
I don't like the warning generated by the compiler, so I'd like to reduce the number of generic types. I thought I could use ICollection, but IReadOnlyCollection<T> doesn't "inherit" from ICollection
When I use the validator I have to supply all the types.
Is there a better solution than the one I currently have?
答案1
得分: 2
在你的第二次尝试中,你需要将TElement
指定为泛型参数,而不是IReadOnlyCollection<...>
,然后在PropertyValidator<T, IReadOnlyCollection<TElement>>
中使用它:
public class CollectionSizesMatchValidator<T, TElement> : PropertyValidator<T, IReadOnlyCollection<TElement>>
{
public override bool IsValid(ValidationContext<T> context, IReadOnlyCollection<TElement> value)
{
throw new NotImplementedException();
}
public override string Name { get; }
}
或者,只需按照文档中的说明禁用警告。
英文:
In your second attempt you need to specify TElement
as generic parameter, not IReadOnlyCollection<...>
and then use it for PropertyValidator<T, IReadOnlyCollection<TElement>>
:
public class CollectionSizesMatchValidator<T, TElement> : PropertyValidator<T, IReadOnlyCollection<TElement>>
{
public override bool IsValid(ValidationContext<T> context, IReadOnlyCollection<TElement> value)
{
throw new NotImplementedException();
}
public override string Name { get; }
}
Or just disable the warning as explained in the docs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论