如何使用反射来设置此对象的 属性?

How can I use reflection to set this object's property?

我有一个正在使用的外部库,即 Aspose.Email.dll(在 NuGet 上可用)。它有一个 PageInfo class。 Go To DefinitionVisual 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);

问题是 SetValue 出错 Property set method not found.

Getter-只有属性没有 setter。他们使用只能在构造函数中设置的 readonly 支持字段。

您可以将属性更改为私有 setter,例如

public int ItemsPerPage { get; private set; }

如果您无权访问代码,您可以使用 GetField 找到匹配字段并设置其值。

typeof(PageInfo).GetTypeInfo().DeclaredFields
    .First(f => f.Name.Contains("ItemsPerPage")).SetValue(result, 1);