c#如何将输入缓冲区属性值获取为字符串

c#如何将输入缓冲区属性值获取为字符串,c#,reflection,propertyinfo,C#,Reflection,Propertyinfo,我需要在inputbuffer中获取每个属性的值,我可以获取属性的名称,但无法获取值,我需要在字典中添加名称和值。这是我的代码: public override void Input0_ProcessInputRow(Input0Buffer Row) { Dictionary<string, string> body = new Dictionary<string, string>(); foreach (PropertyInfo inputColum

我需要在inputbuffer中获取每个属性的值,我可以获取属性的名称,但无法获取值,我需要在字典中添加名称和值。这是我的代码:

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    Dictionary<string, string> body = new Dictionary<string, string>();

    foreach (PropertyInfo inputColumn in Row.GetType().GetProperties())
    {
        if (!inputColumn.Name.EndsWith("IsNull"))
                body.Add(inputColumn.Name, Row.GetType().GetProperty(inputColumn.Name).GetValue(Row).ToString() );
    }
}
public override void Input0\u ProcessInputRow(Input0Buffer行)
{
字典体=新字典();
foreach(Row.GetType().GetProperties()中的PropertyInfo inputColumn)
{
如果(!inputColumn.Name.EndsWith(“IsNull”))
Add(inputColumn.Name,Row.GetType().GetProperty(inputColumn.Name).GetValue(Row.ToString());
}
}

我得到了这个异常:对象引用没有设置为对象的实例,您应该为每个方法调用使用变量,比如
var rowType=Row.GetType()

例如,
Row.GetType().GetProperty(inputColumn.Name)
可以替换为
inputColumn

您可以在同一方法中重用变量,堆栈跟踪将显示引发null引用的行。请检查堆栈跟踪,它将显示导致错误的方法名称


我假设
.GetValue(Row)
返回null。

您只需在
inputColumn
对象上调用
GetValue
,如下所示:

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    Dictionary<string, string> body = new Dictionary<string, string>();

    foreach (PropertyInfo inputColumn in Row.GetType().GetProperties())
    {
        if (!inputColumn.Name.EndsWith("IsNull"))
        {
            body.Add(inputColumn.Name, 
               (string)inputColumn.GetValue(Row));
        }
    }
}
public void ProcessRow<T>(T item)
{
    var body = typeof(T) // Get the type
        .GetProperties() // Get all properties
        .Where(p => !p.Name.EndsWith("IsNull")) // Exclude properties ending with "IsNull"
        .ToDictionary( // Return a dictionary
            p => p.Name, 
            p => (string) p.GetValue(item));
}
或者,如果要包括其他属性类型(例如
int
),则需要恢复使用
ToString

p => p.GetValue(item).ToString()

这样,您就可以对其他对象类型重用此方法

inputColumn.GetValue(行)
?@DavidG在visual studio中我得到“参数2:无法从对象转换为字符串”肯定,因为
GetValue
返回
object
。如果您知道该类型实际上是一个
字符串
,请将其转换。好的
。ToString
将执行相同的操作(除非它不是字符串时不会抛出),不清楚从何处获取该参数错误。我现在收到此错误:无法转换系统。Int32到System.strings,因为并非所有属性都是字符串。请使用我在答案末尾提供的附加行,或者恢复使用
ToString
而不是强制转换。如果您没有使用我的代码,您需要向我们显示您的真实代码,否则我将无能为力。我已对其进行排序,其中一个属性中有一个空值,它引发了异常,它现在可以工作了,谢谢!
p => p.GetValue(item).ToString()