BCS*_*BCS 0 c# types typedef overloading
我有一大堆的是具有不同的含义很多的整数代码(我宁愿一个通用的解决方案,但对于一个具体的例子:某一天的 - 月月对比的最年与年等).我希望能够基于这些含义重载类构造函数.
例如
int a; // takes role A
int b; // takes role B
var A = new Foo(a); // should call one constructor
var B = new Foo(b); // should call another constructor
Run Code Online (Sandbox Code Playgroud)
现在很明显,这将无法工作,但如果我可以定义一个类型(而不仅仅是一个别名),int但是这个类型的名称是:
typedef int TypeA; // stealing the C syntax
typedef int TypeB;
Run Code Online (Sandbox Code Playgroud)
我可以做我需要的重载,让类型系统跟踪什么是什么.特别是这将允许我确保值不会混淆,例如,作为一年的函数返回的值不用作月中的日期.
有没有办法短的class或struct包装在C#这样做吗?
如果解决方案也适用于浮动和双打,那将是很好的.
Jef*_*tes 13
没有直接的typedef等效项,但您可以执行以下操作:
using TypeA = int;
using TypeB = int;
Run Code Online (Sandbox Code Playgroud)
但是,这只是对类型进行别名而不是创建新的强类型.因此,编译器仍会将它们视为int解析方法调用的时间.
更好的解决方案可能是创建包装int并提供隐式转换的简单包装类,例如:
struct TypeA
{
public TypeA(int value)
{
this.realValue = value;
}
private int realValue;
public static implicit operator int(TypeA value)
{
return this.realValue;
}
public static implicit operator TypeA(int value)
{
return new TypeA(value);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,在大多数情况下,enum更合适.
这可能是关闭,但你不能使用枚举吗?枚举基数是int,但是是键入的,您可以根据传递的枚举类型定义不同的构造函数.