[英]Can I use reflection and a string to get/set the correct property of an object?
[英]How can I use reflection to set this object's property?
我有一個正在使用的外部庫,即Aspose.Email.dll (在NuGet上可用)。 它具有PageInfo
類。 轉到定義在Visual Studio中顯示了以下內容:
using System;
namespace Aspose.Email
{
public class PageInfo
{
protected PageInfo next;
public int AbsoluteOffset { get; }
public int ItemsPerPage { get; }
public bool LastPage { get; }
public virtual PageInfo NextPage { get; }
public int PageOffset { get; }
public int TotalCount { get; }
}
}
長話短說,我需要創建一個PageInfo對象。 如何使用Reflection創建一個並設置其ItemsPerPage
屬性?
我已經試過了:
var result = (PageInfo)FormatterServices.GetUninitializedObject(typeof(PageInfo));
typeof(PageInfo).GetProperty("ItemsPerPage", BindingFlags.Instance | BindingFlags.Public).SetValue(result, 1);
問題是Property set method not found.
SetValue
錯誤Property set method not found.
僅限Getter的屬性沒有setter。 它們使用只能在構造函數中設置的readonly
后備字段。
您可以將屬性更改為具有私有設置器,例如
public int ItemsPerPage { get; private set; }
如果您無權訪問該代碼,則可以使用GetField
查找匹配字段並設置其值。
typeof(PageInfo).GetTypeInfo().DeclaredFields
.First(f => f.Name.Contains("ItemsPerPage")).SetValue(result, 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.