繁体   English   中英

运行时的C#访问对象属性

[英]C# access object properties at runtime

在此处输入图片说明

我正在调用返回此对象的Web服务。 我知道我应该在C#中使用对象反射来访问sentBatchTotal的属性。 但是,我无法为自己一生解决如何使用此属性的问题。 我在这里和MSDN上都看过其他几篇文章,但并没有陷入。

这是我的代码,我在做什么错?

private void button1_Click(object sender, EventArgs e)
{
    prdChal.finfunctions service = new prdChal.finfunctions();
    //Type thisObject = typeof()

    //Type myType = myObject.GetType();
    //IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

    String ThisName = "";
    Object StatusReturn = new Object();

    StatusReturn = service.UpdateGrantBillStatus(fundBox.Text, toBox.Text, fromBox.Text);
    var type = StatusReturn.GetType();
    var propertyName = type.Name;
    //var propertyValue = propertyName.GetValue(myObject, null);error here 
}

不要首先将StatusReturn变量声明为对象类型。

//Object StatusReturn = new Object();

var StatusReturn = service.UpdateGrantBillStatus(fundBox.Text, toBox.Text, fromBox.Text);
if (StatusReturn.Count() > 0)
{
    var fixedAsset = StatusReturn[0];
}
dynamic d = service.UpdateGrantBillStatus(fundBox.Text, toBox.Text, fromBox.Text);
string result = (string)d[0].sentBatchTotal;

以下代码使用反射。

StatusReturn = service.UpdateGrantBillStatus(fundBox.Text, toBox.Text, fromBox.Text);
var type = StatusReturn.GetType();
var pi = type.GetProperty("sentBatchTotal");
if (pi != null) {
    var propertyValue = pi.GetValue(StatusReturn, null);
}

但是,您能否仅使用webservice-method返回类型而不是object? 比起您直接阅读属性而言。

就像是:

WhatEverTypeYourServiceReturns StatusReturn = service.UpdateGrantBillStatus(fundBox.Text, toBox.Text, fromBox.Text);
string sentBatchTotal = StatusReturn.sentBatchTotal;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM