jeudi 17 avril 2014

c# insérer une variable dans une chaîne - Stack Overflow


  Random rnd = new Random();
int ID = rnd.Next(1, 999);
string body = @"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""help here""}";

how could i add the "ID" to the string body in "help here" so it could generate random numbers !




In a typical string inserting scenario, I'd do one of these:


string body = string.Format("My ID is {0}", ID);
string body = "My ID is " + ID;

However, your string is apparently JSON serialized data. I'd expect that I'd want to parse that into a class in order to work with it.


var myObj = JsonConvert.DeserializeObject<MyClass>(someString);
myObj.TID = ID;
// maybe do other things with it, then if I need JSON again...
string body = JsonConvert.SerializeObject(myObj);

One reason to take this approach is to make sure that any data I put in still makes the JSON valid. For example, if my ID were, instead of an int, a string with characters that needed escaping, directly inserting "\"\n\"" would not be the right thing to do.




There are a number of ways to inject values into strings, however it's easy to lose sight of encodings, and cause major breakage.


If you just want to inject a value into another string, you can use:



  • string concatenation

  • string building

  • string formatting


Concatenation:


The simplest and most common way to build strings is by simply concatenating them together with the + operator:


var foo = 5;
var bar = "example-" + foo;

Concatenation can be difficult to read which makes it easy to introduce bugs, but for most simple tasks is the right tool for the job.


In this case, it's a poor choice:


string body = @"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""" + ID.ToString() + @"""}";

String Building


The StringBuilder class is useful for building large strings particularly when built iteratively.


var sb = new StringBuilder();
for (var i = 0; i < 1000; i++) {
sb.Append(i.ToString());
sb.Append(" ");
}
var output = sb.ToString();

It can still be difficult to read and hard to debug, but for cases where you're joining lots of strings together, it's super efficient


In this case, it's a poor choice:


StringBuilder sb = new StringBuilder();
sb.Append(@"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""");
sb.Append(ID.ToString());
sb.Append(@"""}");
string body = sb.ToString();

String formatting


The string.Format method makes templating data into a string super easy and efficient. If you plan on reusing the same string over and over, using a format string makes it much easier to read and debug code, particularly when there are lots of replacements:


var foo = 5;
var bar = string.Format("example-{0}", foo);

Format strings can also automatically apply culturally accurate formatting to particular data types, so that a DateTime is appropriately displayed, or so that a number has the appropriate number of trailing zeros.


In this case, it's a poor choice:


string string.Format(@"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""{0}""}", ID);

The right choice


You're not dumping data into any old string. That's JSON encoded data. If you just concatenate/build/format in any old value, you can break your string. For example, if the ID variable contained a " character, you'd break the entire JSON dataset.


Additionally, the length of the string and necessary quotes make it super difficult to read, which makes it difficult to maintain. Good luck when you get around to needing to add another formatted value, it's going to be a pain to change any existing value or add in new dynamic ones.


Instead of writing a JSON literal, write an object and encode it to JSON:


var bodyData =
new
{
currency = "country",
gold = 1,
detail = "detailid-979095986",
tId = ID //here's where you set the ID
};
var jss = new JavaScriptSerializer();
var body = jss.Serialize(bodyData);

This code is much easier to modify when the data changes, and will actually encode your data correctly. You don't need to worry about all those annoying double quote characters any more either.




You can use the


String.Format(@"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""{0}""}", ID)

Since this is params object[], you can use as many {n} as you want.




You could try this:


string body = @"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""" + ID + @"""}";

You can also use string.Concat:


string body = string.Concat(@"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""", ID, @"""}");



Instead of using on string, you could concatenate strings together using +, which would allow you to insert text between the generated strings.


string body = @"***" + ID + @"***";


  Random rnd = new Random();
int ID = rnd.Next(1, 999);
string body = @"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""help here""}";

how could i add the "ID" to the string body in "help here" so it could generate random numbers !



In a typical string inserting scenario, I'd do one of these:


string body = string.Format("My ID is {0}", ID);
string body = "My ID is " + ID;

However, your string is apparently JSON serialized data. I'd expect that I'd want to parse that into a class in order to work with it.


var myObj = JsonConvert.DeserializeObject<MyClass>(someString);
myObj.TID = ID;
// maybe do other things with it, then if I need JSON again...
string body = JsonConvert.SerializeObject(myObj);

One reason to take this approach is to make sure that any data I put in still makes the JSON valid. For example, if my ID were, instead of an int, a string with characters that needed escaping, directly inserting "\"\n\"" would not be the right thing to do.



There are a number of ways to inject values into strings, however it's easy to lose sight of encodings, and cause major breakage.


If you just want to inject a value into another string, you can use:



  • string concatenation

  • string building

  • string formatting


Concatenation:


The simplest and most common way to build strings is by simply concatenating them together with the + operator:


var foo = 5;
var bar = "example-" + foo;

Concatenation can be difficult to read which makes it easy to introduce bugs, but for most simple tasks is the right tool for the job.


In this case, it's a poor choice:


string body = @"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""" + ID.ToString() + @"""}";

String Building


The StringBuilder class is useful for building large strings particularly when built iteratively.


var sb = new StringBuilder();
for (var i = 0; i < 1000; i++) {
sb.Append(i.ToString());
sb.Append(" ");
}
var output = sb.ToString();

It can still be difficult to read and hard to debug, but for cases where you're joining lots of strings together, it's super efficient


In this case, it's a poor choice:


StringBuilder sb = new StringBuilder();
sb.Append(@"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""");
sb.Append(ID.ToString());
sb.Append(@"""}");
string body = sb.ToString();

String formatting


The string.Format method makes templating data into a string super easy and efficient. If you plan on reusing the same string over and over, using a format string makes it much easier to read and debug code, particularly when there are lots of replacements:


var foo = 5;
var bar = string.Format("example-{0}", foo);

Format strings can also automatically apply culturally accurate formatting to particular data types, so that a DateTime is appropriately displayed, or so that a number has the appropriate number of trailing zeros.


In this case, it's a poor choice:


string string.Format(@"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""{0}""}", ID);

The right choice


You're not dumping data into any old string. That's JSON encoded data. If you just concatenate/build/format in any old value, you can break your string. For example, if the ID variable contained a " character, you'd break the entire JSON dataset.


Additionally, the length of the string and necessary quotes make it super difficult to read, which makes it difficult to maintain. Good luck when you get around to needing to add another formatted value, it's going to be a pain to change any existing value or add in new dynamic ones.


Instead of writing a JSON literal, write an object and encode it to JSON:


var bodyData =
new
{
currency = "country",
gold = 1,
detail = "detailid-979095986",
tId = ID //here's where you set the ID
};
var jss = new JavaScriptSerializer();
var body = jss.Serialize(bodyData);

This code is much easier to modify when the data changes, and will actually encode your data correctly. You don't need to worry about all those annoying double quote characters any more either.



You can use the


String.Format(@"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""{0}""}", ID)

Since this is params object[], you can use as many {n} as you want.



You could try this:


string body = @"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""" + ID + @"""}";

You can also use string.Concat:


string body = string.Concat(@"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""", ID, @"""}");


Instead of using on string, you could concatenate strings together using +, which would allow you to insert text between the generated strings.


string body = @"***" + ID + @"***";

0 commentaires:

Enregistrer un commentaire