简体   繁体   English

如何在通用 class 中定义 TItem 的类型,或将 class 名称设置为变量?

[英]How to define the type of TItem inside of generic class, or set class name as a variable?

How can I create a class variable (or class alias) on top of the file and use that variable name later in the file?如何在文件顶部创建 class 变量(或 class 别名)并稍后在文件中使用该变量名称? My goal is to reuse (copy) this class in several places and change only the class type variable on top of the file.我的目标是在几个地方重用(复制)这个 class 并仅更改文件顶部的 class 类型变量。 Otherwise, every time I copy this class, I have to replace all class names in the file, which is more than a thousand lines.不然每次复制这个class,都要把文件里所有的class名字全部替换掉,一千多行。 Sometimes you just miss some of them.有时你只是想念其中的一些。 Of course, not all classes have the same properties, and when I'll change the class name from Address to Employee, VS editor will highlight those parts -当然,并非所有类都具有相同的属性,当我将 class 名称从 Address 更改为 Employee 时,VS 编辑器将突出显示这些部分 -

"Employee does not contain member called 'StreetNo'" “员工不包含名为‘StreetNo’的成员”

Then I will take care of that red squiggly lines.然后我会处理那些红色的波浪线。

Is it possible?可能吗? For example:例如:

var model = Employee;  // Employee is a class

and below use it as follows:并在下面按如下方式使用它:

model newInstance = new model();

I tried to use generics (TItem), but I cannot assign the type of TItem inside of generic class:我尝试使用 generics (TItem),但我无法在通用 class 内分配 TItem 的类型:

public class Foo<TItem> where TItem : Employee
{
    // where TItem : Employee - this part of code only sets constraint, but doesn't set TItem equal to Employee - (e.g. TItem = Employee)
}

This is a very basic example of a razor component, which in fact is a partial class.这是 razor 组件的一个非常基本的示例,它实际上是部分 class。 I just simplified the case.我只是简化了案例。 Any ideas?有任何想法吗?

You can try using aliases :您可以尝试using别名

using Model = Employee;

And later in the code:稍后在代码中:

Model newInstance = new Model();

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

相关问题 如何在泛型类中设置泛型类型 - How do I set a generic type inside a generic class 如何在通用表模板内的 Blazor WebAssembly 中的虚拟化组件中指定 TItem 的类型 - How to specify the type of TItem in Virtualize Component in Blazor WebAssembly inside a Generic Table Template 如何使用泛型类型定义接口或类,而泛型类型拥有泛型类型 - How define a interface or class with a generic type who's generic type holds a generic type 泛型类,如何在运行时设置类型? - generic class, how to set the type in runtime? 如何在变量中存储将用于代替通用类的类的名称? - How to store in a variable the name of the class that will be used in place of a generic class? (type)(object)变量在泛型类中使用重载的唯一方法是什么? - (type)(object)Variable the only way to use an overload inside a generic class? 如何定义一个泛型方法来返回派生类类型的实例? - How to define a generic method that returns an instance of the deriving class type? 创建泛型类的实例,如何轻松设置调用类的类型 - Creating an instance of generic class, how to easily set the type to the calling class 将类名传递给泛型类型 - Pass class name to generic type 为类型名称创建一个通用类 - create a generic class for the type name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM