我正在使用文件助手,我把我的课程[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);
}
}
我可以用什么来检查该属性是否在具有该值的类上?
修改
这就是我所看到的可用属性
答案 0 :(得分: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();