24 AĞUSTOS 2009, PAZARTESİ
Nasıl kullanıcı dostu bir dize daha oluşturabilirim.biçim sözdizimi
Bir programda çok uzun bir dize oluşturmak için ihtiyacım var, ve Dize kullanarak.Biçimi. Karşı karşıya olduğum problem 8-10'dan fazla parametre varsa tüm numaraları takip.
Bir de buna benzer bir sözdizimi kabul edeceğini aşırı çeşit yaratmak mümkün değil mi?
String.Format("You are {age} years old and your last name is {name} ",
{age = "18", name = "Foo"});
CEVAP
24 AĞUSTOS 2009, PAZARTESİ
Nasıl anonim türleri (örnek aşağıda) hem çalışır, aşağıdaki, ya da normal tip (Alan, varlıklar, vb):
static void Main()
{
string s = Format("You are {age} years old and your last name is {name} ",
new {age = 18, name = "Foo"});
}
kullanarak:
static readonly Regex rePattern = new Regex(
@"(\{ )([^\}] )(\} )", RegexOptions.Compiled);
static string Format(string pattern, object template)
{
if (template == null) throw new ArgumentNullException();
Type type = template.GetType();
var cache = new Dictionary<string, string>();
return rePattern.Replace(pattern, match =>
{
int lCount = match.Groups[1].Value.Length,
rCount = match.Groups[3].Value.Length;
if ((lCount % 2) != (rCount % 2)) throw new InvalidOperationException("Unbalanced braces");
string lBrace = lCount == 1 ? "" : new string('{', lCount / 2),
rBrace = rCount == 1 ? "" : new string('}', rCount / 2);
string key = match.Groups[2].Value, value;
if(lCount % 2 == 0) {
value = key;
} else {
if (!cache.TryGetValue(key, out value))
{
var prop = type.GetProperty(key);
if (prop == null)
{
throw new ArgumentException("Not found: " key, "pattern");
}
value = Convert.ToString(prop.GetValue(template, null));
cache.Add(key, value);
}
}
return lBrace value rBrace;
});
}
Bunu Paylaş:
Nasıl daha sonra düz metin alma için e...
Nasıl değişmez bir " baskı miyim;{}&qu...
Nasıl Dize % kaçmak için.Biçim?...
Nasıl birden fazla satır içine daha fa...
Dize tek boşluk ile 2 veya daha fazla ...