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

像这样获取分隔符字段:

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

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