如何在C#中将属性作为参数传递

时间:2018-05-06 10:40:22

标签: c#

假设我有一个班级

String mUrl= <YOUR_URL>;
InputStreamVolleyRequest request = new     InputStreamVolleyRequest(Request.Method.GET, mUrl,
    new Response.Listener<byte[]>() { 
         @Override 
         public void onResponse(byte[] response) { 
       // TODO handle the response 
        try { 
        if (response!=null) {

          FileOutputStream outputStream;
          String name=<FILE_NAME_WITH_EXTENSION e.g reference.txt>;
            outputStream = openFileOutput(name, Context.MODE_PRIVATE);
            outputStream.write(response);
            outputStream.close();
            Toast.makeText(this, "Download complete.", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
        e.printStackTrace();
    }
  }
} ,new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
  }
}, null);
      RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
      mRequestQueue.add(request);

我有一个方法class Item { public int A {get; set} public int B {get; set} public int C {get; set} } ,它应该遍历parseData(List<Item> items, <reference to property>)并从每个项目中只获取必需的属性。在C#中最有效的方法是什么?我应该使用items吗(但我不明白该怎么做)?

2 个答案:

答案 0 :(得分:2)

要获取属性,您可以使用Func<Item, T>

// I don't know what this method returns so I used "void".
public void ParseData<T>(List<Item> items, Func<Item, T> propertySelector) {
    // as an example, here's how to get the property of the first item in the list
    var firstItemsProperty = propertySelector(items.First());
    ...
}

您可以通过传递lambda表达式来调用此方法:

ParseData(itemList, x => x.Property1) // "Property1" is a property declared in "Item"

答案 1 :(得分:1)

如果你愿意,可以反思一下

public void ParseData(List<Item> items, String PropertyName)
{
    foreach (Item item in items)
    {
        var prop = typeof(Item).GetProperty(PropertyName).GetValue(item, null);            
    }
}