我可以使用反射动态构建如下所示的类吗?没有方法,只有公共变量,有些有自定义属性。
是否需要 .Emit 方法(从我所见,“Emit”看起来有点挑战性)。
我正在使用来自www.FileHelpers.net的软件,它需要一个类。我所有的文件定义都在一个数据库表中,我想让一切变得更加动态(即当文件中出现新列时没有代码更改)。
[FileHelpers.DelimitedRecord(",")]
public class FileRow
{
[FileHelpers.FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string Borrower_First_Name;
[FileHelpers.FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string Borrower_Last_Name;
public string Borrower_Email;
}
更新 1:根据 Vlad 在下面的回答,我需要引用 DLL,我是这样做的:
// need to reference the FileHelpers.dll from our own .exe directory
string diskFilenameFileHelpersDLL =
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location) +
@"\FileHelpers.dll";
更新 2:此外,按照 Vlad 的建议,这就是我调用 FileHelper 并遍历结果的方式。我可能会将数据传输到列表中。
Assembly assembly = compiledResult.CompiledAssembly;
// Simple Data Test
lineContents = "John,Doe,jd123456@yahoo.com";
FileHelperEngine engine = new FileHelperEngine(assembly.GetType("FileRow"));
// FileRow[] FileRowArray = (FileRow[])engine.ReadString(lineContents);
Object[] FileRowArray = engine.ReadString(lineContents);
Object myObject = FileRowArray[0]; // only 1 row of data in this example
// Get the type handle of a specified class.
Type myType = assembly.GetType("FileRow");
// Get the fields of the specified class.
FieldInfo[] myField = myType.GetFields();
Console.WriteLine("\nDisplaying fields values:\n");
for (int i = 0; i < myField.Length; i++)
{
Object objTest = myField.GetValue(i);
string tempName = myField[i].Name;
Object objTempValue = myField[i].GetValue(myObject);
string tempValue = System.Convert.ToString(objTempValue);
Console.WriteLine("The value of {0} is: {1}",
tempName, tempValue);
}