简体   繁体   中英

C# access object properties at runtime

在此处输入图片说明

I'm calling a web service that is returning this object. I know I should be using object reflection in C# to access the property of sentBatchTotal . However, I can't for the life of me figure out how to get to this property. I have looked at several other articles here and on MSDN but it's just not sinking in.

Here is my code, what am I doing wrong?

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 
}

Don't declare your StatusReturn variable as an object type first.

//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;

The following code uses reflection.

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);
}

But can't you just the webservice-method return-type instead of object? Than you can just read the property directly.

Something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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