简体   繁体   中英

How can I tell if a variable does not end in a hyphen?

I have c# variables such as

var a = "ABC";
a = "def-";
a = "-";

Is there some simple test I could do so I could check if the variable does not end in a hyphen?

if ( xxx )
if (a.ToString().EndsWith("-")) ...

在劳埃德(Lloyd)关于适用于

if ((a!=null) && (a.ToString().EndsWith("-"))) ...

"Does not end"

if (!(a.EndsWith("-"))){
  // Do something
}

Doc: http://msdn.microsoft.com/en-us/library/2333wewz.aspx

Warning. This may be an editorial

Revisit your design.

The question has code-smell all over it. I infer that the embedded hyphen has some "business meaning." Such a thing should be embodied as a class, field, property, etc. Such a properly named thing will convey it's meaning/intent. But the more important issue is maintainability.

Just yesterday I ran into this in our own code. Hear me now and believe me later. Encoding variable names may seem expedient but you're just setting yourself up for a world of hurt when it comes time to modify it or simply helping the next poor coder understand it.

At the very least, if you insist on encoding variable names, separate that encode/decode into an independent class. And for g0d's sake don't name that class/methods "EncodeName" or the like!!

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