简体   繁体   中英

Defining new simple types in C# ala Delphi

I would like to define new 'simple' types like this (in delphi):

type
  TString2        = string[2];
  TString10       = string[10];
  TYesNo          = (isNull=-1, isNo=0,   isYes=1);
  TBit2           = 0..3;

And then, use that inside my class-fields, like this (in delphi again):

TCMDchild = class(TCMDParent)
strict protected
    fSgMrMs:        TString2;
    fSgIsMale:      TYesNo;
    fSgValue1:      TBit2;
    ......

¿ Are there any way to get the same easy " simple type construction " in C# (VS2010)?

Thanks for your comments.

Yes you can do that

You can use using keyword to do something like delphi Type or typedef in C and C++.

More information can be found here:

https://stackoverflow.com/a/9258058/970420

No, there aren't any type aliases like that in C#. It was not included, because most of the time it has been used to hide away what the code does instead of making the code clearer.

Besides, you don't specify the size of a string in C#, and there are no range limited numbers. You can use properties that check the values when you set them.

For the YesNo type you can use an 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;
    }
  }

}

Note: You should try to use more descriptive names than things like "fSgMrMs".

For the TYesNo you can use an enum:

public enum TYesNo
{
    IsNull = -1,
    No = 0,
    Yes = 1
}

For the others you could use properties and check the lenght in the 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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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