Removing properties of an inherited object in C#

2019-07-13 08:10发布

问题:

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.

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

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).

Something like:

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()
    {
    }
}

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.

回答1:

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()
    {

    }
}


回答2:

See here in the "Defining Exception classes" paragraph to see how to create a custom serializable exception.

Relevant part from the article:

[Serializable()]
public class InvalidDepartmentException : System.Exception
{
    public InvalidDepartmentException() : base() { }
    public InvalidDepartmentException(string message) : base(message) { }
    public InvalidDepartmentException(string message, System.Exception inner) : base(message, inner) { }

    // A constructor is needed for serialization when an
    // exception propagates from a remoting server to the client. 
    protected InvalidDepartmentException(System.Runtime.Serialization.SerializationInfo info,
        System.Runtime.Serialization.StreamingContext context) { }
}


回答3:

Have you tried using the IgnoreDataMemberAttribute or the NonSerializedAttribute?

[IgnoreDataMember]
// or
[NonSerialized]
public override System.Reflection.MethodBase TargetSite
{
    // ...
}