[英]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.