在c#和Delphi中定义新的简单类型
本文关键字:简单 类型 定义 Delphi | 更新日期: 2023-09-27 18:01:15
我想定义这样的新的'简单'类型(在delphi中):
type
TString2 = string[2];
TString10 = string[10];
TYesNo = (isNull=-1, isNo=0, isYes=1);
TBit2 = 0..3;
然后,在我的类字段中使用它,像这样(还是在delphi中):
TCMDchild = class(TCMDParent)
strict protected
fSgMrMs: TString2;
fSgIsMale: TYesNo;
fSgValue1: TBit2;
......
在c# (VS2010)中有什么方法可以获得同样简单的"简单类型结构"吗?感谢您的评论
可以的
您可以使用使用关键字来完成类似于delphi Type或typedef在C和c++中的功能。
更多信息可以在这里找到:
https://stackoverflow.com/a/9258058/970420不,c#中没有这样的类型别名。没有包括它,因为大多数时候它被用来隐藏代码的功能,而不是使代码更清晰。
此外,c#中不需要指定字符串的大小,也没有范围限制。您可以使用属性在设置值时检查这些值。
对于YesNo
类型,可以使用enum:
public enum YesNo {
No = 0,
Yes = 1,
Null = -1
}
class CommandChild : CommandParent {
private string _fSgMrMs;
private string _fSgValue1;
public string fSgMrMs {
get { return _fSgMrMs; }
set {
if (value.Length > 2) {
throw new ArgumentException("The length of fSgMrMs can not be more than 2.");
}
_fSgMrMs = value;
}
}
public YesNo fSgIsMale { get; set; }
public int fSgValue1 {
get { return _fSgValue1; }
set {
if (value < 0 || value > 3) {
throw new ArgumentException("The value of fSgValue1 hase to be between 0 and 3.");
}
_fSgValue1 = value;
}
}
}
注意:您应该尝试使用比"fSgMrMs"更具有描述性的名称。
对于TYesNo,您可以使用enum:
public enum TYesNo
{
IsNull = -1,
No = 0,
Yes = 1
}
对于其他的,你可以使用属性并检查setter中的长度:
public class TCmdChild : TCmdParent
{
public TYesNo FSgIsMale { get; set; }
protected string fSgMrMs;
public string FSgMrMs
{
get { return fSgMrMs; }
set
{
if(value.Length > 2)
throw new OutOfRangeException("Value.Length needs to be <= 2");
fSgMrMs = value;
}
}
}