2012-12-12 123 views
0

我正在使用文件助手,我把我的課上[DelimitedRecord("|")]可能從屬性獲取價值?

我想檢查,如果值是「|」如果不是那麼我想拋出一個例外..

public void WriteResults<T>(IList<T> resultsToWrite, string path, string fileName) where T: class 
     {  
      var attr = (DelimitedRecordAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(DelimitedRecordAttribute)); 

      if (attr.HasValue("|")) // has value does not exist. 
      { 
       FileHelperEngine<T> engine = new FileHelperEngine<T>(); 
       engine.HeaderText = String.Join("|", typeof(T).GetFields().Select(x => x.Name)); 

       string fullPath = String.Format(@"{0}\{1}-{2}.csv", path, fileName, DateTime.Now.ToString("yyyy-MM-dd")); 

       engine.WriteFile(fullPath, resultsToWrite); 
      } 


     } 

我可以用什麼來檢查該屬性是在該類與該值?

編輯

這是我看到的可用屬性

available properties

回答

3

可以檢索DelimitedRecordAttribute一個實例是這樣的:

// t is an instance of the class decorated with your DelimitedRecordAttribute 
DelimitedRecordAttribute myAttribute = 
     (DelimitedRecordAttribute) 
     Attribute.GetCustomAttribute(t, typeof (DelimitedRecordAttribute)); 

如果DelimitedRecordAttribute公開的一種手段獲取參數(它顯示你可以通過這種方式(通常是屬性)訪問該值,例如,是這樣的:

var delimiter = myAttribute.Delimiter 

http://msdn.microsoft.com/en-us/library/71s1zwct.aspx

UPDATE

因爲似乎沒有在你的情況下,一個公共屬性,你可以使用反射來枚舉非公開領域,看看如果你可以找到一個包含該值的字段,例如像

FieldInfo[] fields = myType.GetFields(
        BindingFlags.NonPublic | 
        BindingFlags.Instance); 

foreach (FieldInfo fi in fields) 
{ 
    // Check if fi.GetValue() returns the value you are looking for 
} 

更新2

如果這個屬性是從filehelpers.sourceforge.net,現場你是後

internal string Separator; 

該類完整的源代碼是

[AttributeUsage(AttributeTargets.Class)] 
public sealed class DelimitedRecordAttribute : TypedRecordAttribute 
{ 
    internal string Separator; 

/// <summary>Indicates that this class represents a delimited record. </summary> 
    /// <param name="delimiter">The separator string used to split the fields of the record.</param> 
    public DelimitedRecordAttribute(string delimiter) 
    { 
     if (Separator != String.Empty) 
      this.Separator = delimiter; 
     else 
      throw new ArgumentException("sep debe ser <> \"\""); 
    } 


} 

更新3

得到這樣的分隔欄:

FieldInfo sepField = myTypeA.GetField("Separator", 
         BindingFlags.NonPublic | BindingFlags.Instance); 

string separator = (string)sepField.GetValue(); 
+0

雅我一直在尋找在MSDN的例子。我沒有看到任何可以使用期望的屬性,即TypeId什麼是對象。儘管存儲管道,但我沒有看到任何東西。 – chobo2

+0

@ chobo2:如果沒有屬性暴露該值,則可能仍然可以通過反射來獲取它(通過反射肯定可以得到它,除非該值永遠不會存儲在實例中)。 –

+0

@ chobo2:更新我的帖子,向您展示如何枚舉非公有字段(如果沒有公共屬性,最有可能存儲值的地方)。你需要檢查這些字段,看看是否擁有你以後的價值。 –