2013-01-12 45 views
1

我需要解析我的類爲了某種目的,爲每個屬性提供特定的文本字符串。linq查詢來解析我的類

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"} 
+3

你真的要解析你的類的*源*嗎?你沒有編譯版本嗎? –

+0

是喬恩,我處於一種需要所需輸出爲文本的情況。 –

+0

我不是在談論*輸出* - 我在談論*輸入*。 –

回答

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

+0

我無法在VS2010中編譯此代碼 –

+0

「無法編譯」不是錯誤消息。你有什麼問題?這不是獨立的代碼,它至少需要在某個類的方法中。另外,您至少需要導入演示代碼示例中包含的庫。 **編輯**:我只是通過複製粘貼演示代碼(未編輯)到VS 2010中的新項目進行測試,並且工作正常。 – mellamokb

+0

這個作品非常感謝你!!!!!! –

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); 
    } 
} 
+0

+1 http://ideone.com/3Hq1P5 – mellamokb

+0

無法在vs2020中編譯無法找到類型或命名空間名稱'MyPropertyAttribute' –

+1

'MyPropertyAttribute'您的屬性的名稱。您需要使用using語句來限定該屬性在其中定義的名稱空間,並引用包含該名稱空間的項目(如果它是在單獨的項目中定義的)。 –