设置没有 Setter 的 C# 属性 [英] Set C# Property that has no Setter

查看:103
本文介绍了设置没有 Setter 的 C# 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,有 Exception 类.出于测试目的,我希望能够将其 StackTrace 属性设置为任意字符串.StackTrace 没有 setter,所以我的第一次尝试是尝试使用反射:

In C#, there is the Exception class. For the purposes of testing, I would like to be able to set its StackTrace property to arbitrary strings. StackTrace has no setter, so my first attempt was to try using reflection:

Exception instance = new Exception("Testing");
PropertyInfo propertyInfo = typeof(Exception).GetProperty("StackTrace");
propertyInfo.SetValue(instance, "Sample StackTrace value", null);

这会产生运行时错误:

System.ArgumentException:未找到属性设置方法.

有什么方法可以设置 StackTrace 属性?更一般地说,有没有办法设置缺少 setter 的属性?

Is there any way I could set the StackTrace property? More generally, is there a way to set a property that lacks a setter?

推荐答案

您可以派生自己的异常类并覆盖 StackTrace 属性,该属性是虚拟的:

You could derive your own exception class and override the StackTrace property, which is virtual:

public sealed class MyException: Exception
{
    public MyException(string message, string stackTrace): base(message)
    {
        _stackTrace = stackTrace;
    }

    public override string StackTrace
    {
        get
        {
            return _stackTrace;
        }
    }

    private readonly string _stackTrace;
}

请注意,要正确执行此操作,您应该真正实现所有标准异常构造函数,但对于单元测试而言,这可能不是绝对必要的.

Note that to do this properly, you should really implement all the standard exception constructors, but for unit testing this might not be strictly necessary.

请参阅设计自定义异常 了解更多详情:

See Designing Custom Exceptions for more details:

这篇关于设置没有 Setter 的 C# 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆