1

各プロパティの特定のテキスト文字列を作成するために、何らかの目的でクラスを解析する必要があります。

 namespace MyNameSpace
    {
        [MyAttribute]
        public class MyClass
        {

            [MyPropertyAttribute(DefaultValue = "Default Value 1")]
            public static string MyProperty1
            {
                get { return "hello1"; }
            }

            [MyPropertyAttribute(DefaultValue = "Default Value 2")]
            public static string MyProperty2
            {
                get { return "hello2"; }
            }

        }
    }

これは、このクラスが存在するファイルを解析するための私のlinqクエリです

var lines =
    from line in File.ReadAllLines(@"c:\someFile.txt")
        where line.Contains("public static string ")
    select line.Split(' ').Last();


    foreach (var line in lines)
    {
         Console.WriteLine(string.Format("\"{0}\", ", line));
    }

以下を出力しようとしていますが、これに対するlinqクエリの書き方がわかりません。

{"MyProperty1", "Default Value 1"}
{"MyProperty2", "Default Value 2"}
4

2 に答える 2

1

これはどう?

foreach (var propertyInfo in typeof (MyClass).GetProperties()) {
    var myPropertyAttribute =
        propertyInfo.GetCustomAttributes(false).Where(attr => attr is MyPropertyAttribute).SingleOrDefault<MyPropertyAttribute>();
    if (myPropertyAttribute != null) {
        Console.WriteLine("{{\"{0}\",\"{1}\"}}", propertyInfo.Name, myPropertyAttribute.DefaultValue);
    }
}
于 2013-01-12T02:16:08.593 に答える
0

正規表現はより簡単な解決策かもしれません:

var str = File.ReadAllLines(@"c:\someFile.txt");
var regex =
    @"\[MyPropertyAttribute\(DefaultValue = ""([^""]+)""\)\]" +
    @"\s+public static string ([a-zA-Z0-9]+)";

var matches = Regex.Matches(str, regex);

foreach (var match in matches.Cast<Match>()) {
    Console.WriteLine(string.Format("{{\"{0}\", \"{1}\"}}", 
        match.Groups[2].Value, match.Groups[1].Value));
}

出力例:

{"MyProperty1", "Default Value 1"}
{"MyProperty2", "Default Value 2"}

デモ: http://ideone.com/D1AUBK

于 2013-01-12T02:13:39.847 に答える