如何在C#中为内置类型添加别名? [英] How to alias a built-in type in C#?
问题描述
所以在C ++中,我习惯于做到:
So in C++, I'm used to being able to do:
typedef int PeerId;
这使我可以使类型更具自记录性,但同时也可以使PeerId表示随时更改为其他类型,而无需更改所有代码。如果需要,我甚至可以将PeerId转换为类。我想在C#中拥有这种可扩展性,但是我在弄清楚如何在C#中为'int'创建别名时遇到了麻烦。
This allows me to make a type more self-documenting, but additionally also allows me to make PeerId represent a different type at any time without changing all of the code. I could even turn PeerId into a class if I wanted. This kind of extensibility is what I want to have in C#, however I am having trouble figuring out how to create an alias for 'int' in C#.
我想我可以使用using语句,但是我相信它仅在当前文件中具有作用域,因此将不起作用(别名需要在多个文件之间进行访问而无需重新定义)。我也不能从内置类型派生一个类(但是通常这是我要为引用类型(例如List或Dictionary)加别名的方法。我不确定该怎么办。有想法吗?
I think I can use the using statement, but it only has scope in the current file I believe, so that won't work (The alias needs to be accessible between multiple files without being redefined). I also can't derive a class from built-in types (but normally this is what I would do to alias ref-types, such as List or Dictionary). I'm not sure what I can do. Any ideas?
推荐答案
您可以(ab)使用隐式转换:
You could (ab)use implicit conversions:
struct PeerId
{
private int peer;
public static implicit operator PeerId(int i)
{
return new PeerId {peer=i};
}
public static implicit operator int(PeerId p)
{
return p.peer;
}
}
这与int占用相同的空间,而您可以做到:
This takes the same space as an int, and you can do:
PeerId p = 3;
int i = p;
但是我同意您可能不需要。
But I agree you probably don't need this.
这篇关于如何在C#中为内置类型添加别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!