简体   繁体   English

将泛型引入到从非泛型类继承的构造函数中

[英]Introducing Generic Types to a constructor inheriting from non-Generic class

Question: 题:

Is there a work around to be able to use generics in the constructor of a class that inherits from a class that doesn't have generic types defined? 是否有变通办法,可以在从未定义泛型类型的类继承的类的构造函数中使用泛型?


Explanation: 说明:

I am creating a new custom attribute inheriting from the ValidationAttribute class. 我正在创建一个继承自ValidationAttribute类的新自定义属性。 I want to use generic types in the constructor as seen below: 我想在构造函数中使用通用类型,如下所示:

DateValidationAttribute : ValidationAttribute {

   public void DateValidationAttribute <TData>(Expression<Func<TData, DateTime?>> property){ ... }

}

However, this doesn't seem to be allowed as the TData and TProperty generic types aren't recognized as generics. 但是,似乎不允许这样做,因为TData和TProperty泛型类型未被识别为泛型。 In addition I cannot define the generics in the class definition as it inherits from the ValidationAttribute class. 另外,我无法在类定义中定义泛型,因为它是从ValidationAttribute类继承的。 The error I get is that TData and TProperty is not defined. 我得到的错误是未定义TData和TProperty。


Goal: 目标:

The goal of passing and expression down to have a strongly typed way of passing attribute names. 传递和表达的目的在于具有传递属性名称的强类型方法。 I am writing this attribute to compare two properties of a class. 我正在编写此属性以比较类的两个属性。 The implementation below is what it looks like. 下面的实现是它的样子。 Beneath that is how I want the implementation to look like: 在此之下,我希望实现看起来像这样:

Current:

public DateTime? ToDate { get; set; }

[DateValidation("ToDate")]
public DateTime? FromDate { get; set; }

Goal:

public DateTime? ToDate { get; set; }

[DateValidation(prop => prop.ToDate)]
public DateTime? FromDate { get; set; }    

The non-support for generics in attributes is the least of your problems. 在属性中不支持泛型的问题最少。 Attributes can only have a specific subset of types (primitives, enums, String, Type and single-dimensional arrays) as constructor arguments , not lambdas. 属性只能具有特定类型的子集(基元,枚举,字符串,类型和一维数组)作为构造函数参数 ,而不是lambda。 So even if you could use generics you could not do what you're trying to do. 因此,即使您可以使用泛型,也无法做您想做的事情。

Consider using a string as constructor parameter and using nameof() , eg: 考虑使用字符串作为构造函数参数,并使用nameof() ,例如:

[DateValidation(nameof(ToDate))]

This approach keeps the names in sync with the real property name and thus you get the safety you want when refactoring etc. 这种方法使名称与不动产名称保持同步,因此在进行重构等操作时可以获得所需的安全性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM