简体   繁体   中英

How do I declare a variable with hyphen in it

Recently I was facing with a json object name declaration inside class and was able to resolve it with following:

  [JsonProperty("flv-270p")]
        public string flv270p { get; set; }

So If I want to declare flv-270p without JsonProperty how shall I do it?

like :

public string flv270-p { get; set; }

Short answer: you can't.

.NET supports arbitrary member names, including those illegal in CIL languages. However if a language does not support it then you cannot use it, and this includes hyphens and dashes. Auto-properties in C# use < and > in their hidden backing field names for this reason.

C# does let you prefix keywords with the @ symbol to allow you to use it as a variable or member name (eg public int @class or public void @struct(int @interface) but this is for the benefit of consumers.

However c# does not let you use hyphens in names under any circumstances because that character is used for the unary negation and binary subtraction sub operator. A name flv270-p is interpreted as " flv270 minus p ".

You can't:

Valid names are defined as:

identifier:
    available-identifier
    @   identifier-or-keyword
available-identifier:
    An identifier-or-keyword that is not a keyword
identifier-or-keyword:
    identifier-start-character   identifier-part-charactersopt
identifier-start-character:
    letter-character
    _ (the underscore character U+005F) 
identifier-part-characters:
    identifier-part-character
    identifier-part-characters   identifier-part-character
identifier-part-character:
    letter-character
    decimal-digit-character
    connecting-character
    combining-character
    formatting-character
letter-character:
    A Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl
    A unicode-escape-sequence representing a character of classes Lu, Ll, Lt, Lm, Lo, or Nl
combining-character:
    A Unicode character of classes Mn or Mc
    A unicode-escape-sequence representing a character of classes Mn or Mc
decimal-digit-character:
    A Unicode character of the class Nd
    A unicode-escape-sequence representing a character of the class Nd
connecting-character:
    A Unicode character of the class Pc
    A unicode-escape-sequence representing a character of the class Pc
formatting-character:
    A Unicode character of the class Cf
    A unicode-escape-sequence representing a character of the class Cf 

Hyphen-minus is of class Pd and so not allowed in the above.

It is indeed one of the reasons why allowing something of class Pd in names would be a bad idea:

int x-y = 3;
int x = 10;
int y = 2;
int z = x-y; //3 or 8? Impossible to tell if the first line were allowed.

Actually you can use the code like this

public string flv270_p { get; set; }

AND return a reformatted class that REPLACED "-" with "_".

For example, If you have this,

var jsonstring = ApiRequest.DoRequest(ApiRequest.GetBaseUriFor(typeof(SMS), "/sms/json"), new Dictionary<string, string>()
        {
            {"from", request.from},
            {"to", request.to},
            {"text", request.text}
        });

        return JsonConvert.DeserializeObject<SMSResponse>(jsonstring);

Do this,

var jsonstring = ApiRequest.DoRequest(ApiRequest.GetBaseUriFor(typeof(SMS), "/sms/json"), new Dictionary<string, string>()
        {
            {"from", request.from},
            {"to", request.to},
            {"text", request.text}
        }).Replace("-","_");

        return JsonConvert.DeserializeObject<SMSResponse>(jsonstring);

flv-270p is not a valid variable name in C#. Whenever you type something like that in your code, the compiler thinks you are trying to do "flv270 minus p" :)

The other answers give a good explanation as to why you can't do exacwhat you are asking for. That being said, I have encountered situations where I wanted my object metadata to have hyphens for the purpose of formulating descriptive URLs that are optimized for SEO. The Attribute approach you used in the question works, but you can also use conventions to indicate this kind of customization without attributes. One suggestion is to preprocess member names to use either PascalCase and insert a hyphen delimiter in between words. This might cause too much metadata alteration. Another option is to use an underscore '_', which is a legal character in C# names, and to replace underscores with hyphens in your preprocessing. Your question doesnt really say enough about your use case to indicate how this would be implemented/injected in your metadata context, but hopefully these ideas are helpful when you're designing your api.

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