简体   繁体   English

C#:声明要使用的数据类型的常量变量

[英]C#: Declaring a constant variable for datatype to use

Is it possible somehow to define a constant that says what datatype to use for certain variables, similar to generics? 有可能以某种方式定义一个常量,说明用于某些变量的数据类型,类似于泛型? So in a certain class I would have something like the following: 所以在某个课程中,我会有如下内容:

MYTYPE = System.String;

// some other code here

MYTYPE myVariable = "Hello";

From the principle it should do the same as generics but I don't want to write the datatype every time the constructor for this class is called. 从原理上它应该与泛型一样,但我不想在每次调用此类的构造函数时编写数据类型。 It should simply guarantee that for two (or more) variables the same datatype is used. 它应该简单地保证两个(或更多)变量使用相同的数据类型。

Well, you can use a using directive: 好吧,你可以使用using指令:

using MYTYPE = System.String;

However, that isn't really like a typedef - in particular, this code is now perfectly valid: 但是,这并不像typedef - 特别是,此代码现在完全有效:

MYTYPE x = "hello";
string y = "there";
x = y;

The compiler knows they're still the same type. 编译器知道它们仍然是同一类型。

It's not really clear what you're trying to achieve, particularly here: 你真正想要实现的目标并不是很清楚,特别是在这里:

I don't want to write the datatype every time the constructor for this class is called. 每次调用此类的构造函数时,我都不想编写数据类型。

What do you mean? 你什么意思?

Note that using directives are specific to a source file, not to a whole project. 请注意,using指令特定于源文件,而不是整个项目。

You can do that with a using alias: 您可以using别名来执行此using

using MyType = System.String;

however, only on a per-file basis. 但是,仅基于每个文件。 Frankly, it is useful for making a short alias to some complex composite generic type (I'm thinking of "Owin" etc), but other than that, generics are more versatile. 坦率地说,对一些复杂的复合泛型类型(我想到的是“Owin”等)做一个短别名很有用,但除此之外 ,泛型更通用。

You could use an alias: 您可以使用别名:

using System;
using MYTYPE = System.String;

class Program
{
    static void Main()
    {
        MYTYPE f = "Hello";
        Console.WriteLine(f);
    }
}

Yes, with a using alias directive . 是的, 使用alias指令

edit: beaten by a couple of seconds.. 编辑:殴打几秒钟..

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

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