C#의 명명된 문자열 형식 지정
Python과 같은 프로그래밍 언어에서는 위치가 아닌 이름으로 문자열 형식을 지정할 수 있습니다. 예를 들어 다음과 같은 문자열이 있을 수 있습니다.
print '%(language)s has %(#)03d quote types.' % \ {'language': "Python", "#": 2}
이렇게 하면 "Python에는 002개의 인용 유형이 있습니다."가 인쇄됩니다.
C#에는 문자열 형식을 지정하는 기본 제공 방법이 없습니다. 이름으로. 그러나 유사한 결과를 얻을 수 있는 몇 가지 방법이 있습니다.
사전 사용
한 가지 옵션은 사전을 사용하여 변수 이름을 해당 값에 매핑하는 것입니다. 그런 다음 변수 이름을 사용하여 문자열 형식을 지정하는 사용자 정의 문자열 형식 지정 방법에 사전을 전달할 수 있습니다.
예:
public static string FormatStringByName(string format, Dictionary<string, object> values) { // Create a regular expression to match variable names in the format string. var regex = new Regex(@"\{(.*?)\}"); // Replace each variable name with its value from the dictionary. var formattedString = regex.Replace(format, match => values[match.Groups[1].Value].ToString()); return formattedString; }
이 방법을 다음과 같이 사용할 수 있습니다.
var values = new Dictionary<string, object> { { "some_variable", "hello" }, { "some_other_variable", "world" } }; string formattedString = FormatStringByName("{some_variable}: {some_other_variable}", values);
문자열 보간 사용
에서 C# 6.0 이상에서는 문자열 보간을 사용하여 이름으로 문자열 형식을 지정할 수 있습니다. 문자열 보간은 표현식을 문자열에 직접 삽입할 수 있는 기능입니다.
예:
string formattedString = $"{some_variable}: {some_other_variable}";
이렇게 하면 "hello: world"가 인쇄됩니다.
확장 방법
또 다른 옵션은 확장 방법을 사용하여 명명된 문자열을 추가하는 것입니다. 문자열 클래스에 대한 형식 지정 기능. 사용할 수 있는 확장 방법의 예는 다음과 같습니다.
public static class StringExtensions { public static string FormatByName(this string format, object values) { // Get the type of the values object. var type = values.GetType(); // Get the properties of the values object. var properties = type.GetProperties(); // Create a regular expression to match variable names in the format string. var regex = new Regex(@"\{(.*?)\}"); // Replace each variable name with its value from the values object. var formattedString = regex.Replace(format, match => { var property = properties.FirstOrDefault(p => p.Name == match.Groups[1].Value); if (property != null) { return property.GetValue(values).ToString(); } else { return match.Groups[1].Value; } }); return formattedString; } }
이 확장 방법을 다음과 같이 사용할 수 있습니다.
string formattedString = "{some_variable}: {some_other_variable}".FormatByName(new { some_variable = "hello", some_other_variable = "world" });
위 내용은 C#에서 명명된 문자열 형식을 어떻게 얻을 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!