简体   繁体   English

如何从对象到局部变量C#获取值

[英]how get values from object to local variable c#

i have following code please help me how to get values from object 我有以下代码,请帮助我如何从对象获取值

 APIKarho objapi = new APIKarho();
           object obje = objapi.GetBookingFromAPI();

           string ss = obje.booking_id;

在此处输入图片说明

You should cast the object to the class it originally is (what class is the object returned by GetBookingFromAPI() ) before you could access its field/property/method . 在访问其field/property/method之前, GetBookingFromAPI()对象转换为它原来的class (什么类是GetBookingFromAPI()返回的object GetBookingFromAPI() Example: 例:

public MyClass { // suppose this is the original class of the object returned by GetBookingFromAPI
    public int booking_id; 
}

APIKarho objapi = new APIKarho();
object obje = objapi.GetBookingFromAPI();
string ss = ((MyClass)obje).booking_id; //note the casting to MyClass here

You need to find out what type GetBookingFromAPI() returns, and change the type of obje. 您需要找出GetBookingFromAPI()返回的类型,并更改对象的类型。 Just move your mouse over GetBookingFromAPI(). 只需将鼠标移到GetBookingFromAPI()上即可。

GetBookingFromAPIType obje = objapi.GetBookingFromAPI();

string ss = obje.booking_id;

If your api returns an object of an unknown type or a type that you cannot cast to you could use the dynamic keyword. 如果您的api返回的对象类型未知或无法转换为类型,则可以使用dynamic关键字。

dynamic obj = api.GetBookingFromAPI();
string ss = obj.booking_id;

Note that this works only if booking_id is actually a string. 请注意,这仅在booking_id实际上是字符串时才有效。

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

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