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


        }

その属性がその値を持つクラスにあることを確認するには、何を使用できますか?

編集

これは、利用可能なプロパティとして私が見るものです

利用可能なプロパティ

4

1 に答える 1

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

アップデート

あなたのケースにはパブリック プロパティがないように見えるので、リフレクションを使用して非パブリック フィールドを列挙し、値を保持するフィールドを見つけることができるかどうかを確認できます。

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

次のように Separator フィールドを取得します。

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

string separator = (string)sepField.GetValue();
于 2012-12-12T22:43:20.187 に答える