在C#中删除继承对象的属性 [英] Removing properties of an inherited object in C#

查看:469
本文介绍了在C#中删除继承对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个复杂的对象,我可以从中继承并删除忽略某些属性吗?

If I have a complex object, can I inherit from it and remove or ignore certain properties?

如果您不在意为什么,请随时提交答案.

If you don't care why I want to do this, feel free to just submit an answer.

如果您愿意的话,可以阅读此问题.概括起来,我有一个具有单个属性的对象,该属性不能序列化,并且我想序列化整个对象.有问题的对象是System.Exception

If you do care, you can read this question. To summarize it, I have an object that has a single property that is not serializable, and I want to serialize the entire object. The object in question is System.Exception

要解决这个问题,我想简单地创建自己的JsonException对象,继承基本(System.Exception)的所有可爱属性,除了删除(或清空)丑小鸭(Exception.TargetSite).

To get around the problem I wanted to simply create my own JsonException object, inherit all the lovely properties of the base (System.Exception) except remove (or empty) the ugly duckling (Exception.TargetSite).

类似的东西:

public class MyException : Exception
{
    // Note this is not actually possible
    //      just demonstrating what I thought to do in theory
    public override System.Reflection.MethodBase TargetSite
    {
        get
        {
            return null;
        }
    }

    public MyException(string message)
        : base()
    {
    }
}

还请记住,我一直使用.NET 2.0,并且确实不想使用自定义序列化程序(例如 Json.NET ),如果不需要的话.

Also please keep in mind I am stuck with .NET 2.0 and really don't want to use custom serializers (like Json.NET) if I don't have to.

推荐答案

是否在不覆盖TargetSite属性的情况下进行了尝试?我能够做到(但在2.0中无法做到,所以我不确定它是否会像这样对您有用

Did you try it without overriding the TargetSite property? I was able to do it (but not in 2.0, so I'm not sure if it will work for you like this

public class MyException : Exception
{
    public new System.Reflection.MethodBase TargetSite
    {
        get { return null; }
    }

    public MyException() : base()
    {

    }
}

这篇关于在C#中删除继承对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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