简体   繁体   English

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

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

I have an external library I am using, namely Aspose.Email.dll (available on NuGet ). 我有一个正在使用的外部库,即Aspose.Email.dll (在NuGet上可用)。 It has a PageInfo class. 它具有PageInfo类。 Go To Definition shows the following for it in Visual Studio : 转到定义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; }
    }
}

Long story short, I need to create a PageInfo object. 长话短说,我需要创建一个PageInfo对象。 How can I create one using Reflection and also set its ItemsPerPage property? 如何使用Reflection创建一个并设置其ItemsPerPage属性?

I have tried this: 我已经试过了:

var result = (PageInfo)FormatterServices.GetUninitializedObject(typeof(PageInfo));
typeof(PageInfo).GetProperty("ItemsPerPage", BindingFlags.Instance | BindingFlags.Public).SetValue(result, 1);

The problem is that SetValue errors out with Property set method not found. 问题是Property set method not found. SetValue错误Property set method not found.

Getter-only properties do not have setters. 仅限Getter的属性没有setter。 They use a readonly backing field that can only be set in the constructor. 它们使用只能在构造函数中设置的readonly后备字段。

You can change the properties to have private setter, eg 您可以将属性更改为具有私有设置器,例如

public int ItemsPerPage { get; private set; }

If you do not have access to the code, you can find the matching field using GetField and set its value. 如果您无权访问该代码,则可以使用GetField查找匹配字段并设置其值。

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

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

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