gpt4 book ai didi

c# - 确保泛型方法中的参数基于同一类中的参数

转载 作者:行者123 更新时间:2023-11-30 16:42:28 26 4
gpt4 key购买 nike

我有一个泛型类定义如下:

public abstract class BaseValidator<T> : IValidator<T> where T: IEntity
{
//some methods and parameters here
protected void Include<E>(IValidator<E> validator) where E : class , IEntity
{
if (typeof(E) != typeof(T).BaseType)
{
throw new ArgumentException($"Generic class Validator<T> must only Include Validators for base classes");
}
//Some business logic around connecting validators
}
}

Include 方法旨在接收一个 Validator 参数,它使用此参数将验证器彼此绑定(bind),类似于验证器的责任链。我目前有运行时检查以确保 E 是 T 的基类,但我想将其移至编译时检查。

我试图在方法 Include 中添加第二个 where 子句,如下所示:

where T:E

但是 visual studio 提示方法 Include 没有定义类型参数“T”

如果我确实定义了一个类型参数,我会收到一条消息,指出类型参数“T”与外部类的类型参数同名。

如何确保传递到我的方法中的泛型类型是我的 T 实现的基类?


编辑 1:

public class BankAccountValidator : BaseValidator<BankAccount>
{
public BankAccountValidator(IValidator<OwnedProduct> validator)
{
Include(validator);
//Some logic here
}
}

在本例中,BankAccount 实现了 OwnedProduct。因此,当在 BankAccount 上调用验证方法时,它也会在 OwnedProduct 上调用验证。

我想强制您不能将另一个 BankAccountValidator 传递给 BankAccountValidator,或者如果我有一个 BankAccount 不是从中派生的 OwnedCredit 类型,我不能将 OwnedCreditValidator 传递给构造函数。

有大量的验证器并且像这样强类型化可以防止我遇到运行时问题。

最佳答案

public abstract class BaseValidator<T, E> : IValidator<T> 
where E: IEntity
where T: E
{
//some methods and parameters here
protected void Include(IValidator<E> validator)
{
//Some business logic around connecting validators
}
}

public class BankAccountValidator : BaseValidator<BankAccount, OwnedProduct>
{
public BankAccountValidator(IValidator<OwnedProduct> validator)
{
Include(validator);
//Some logic here
}
}

如果 OwnedProductValidator 可以验证自己,那么:

public class OwnedProductValidator : IValidator<OwnedProduct>
{
// IValidator interface implementation
}

public class Program
{
public static void Main()
{
var ownedProductValidator = new OwnedProductValidator();
var bankAccountValidator = new BankAccountValidator(ownedProductValidator);
}
}

如果 OwnedProductValidator 需要一些其他的类验证,那么:

public class OwnedProductValidator : BaseValidator<OwnedProduct, SomeOtherClass>{}

关于c# - 确保泛型方法中的参数基于同一类中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46684700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com