如何动态添加属性到类中

问题描述:

我想创建一个错误类。它有一些静态属性。例如:消息 InnerException Stacktrace 。但我想添加一些动态属性。

I want to create an error class. And it has some static properties. For example : Message, InnerException, Stacktrace, Source. But I want to add some dynamic properties.

如果异常是 FileNotFoundException ,我想添加 FileName 属性。

If exception is a FileNotFoundException, I want to add FileName property.

或者如果它是 SqlException 添加 LineNumber 属性。我不能从 Exception 继承该类,因为,我从Web服务返回该类。我该怎么办?

Or if it is a SqlException, I want to add LineNumber property. And I can't inherit that class from Exception because, I return that class from a web service. How can I do that?

您可以使用C#中的新功能动态创建类似匿名类型

you can create type dynamically using new features in C# like anonymous types

我不知道你是否尝试做类似的事情,但可以实现以下要求

I am not sure if you are trying to do some thing similar, but can achieve the requirement as follows

        public interface IError { }

        public class ErrorTypeA : IError
        { public string Name; }

        public class ErrorTypeB : IError
        {
            public string Name;
            public int line;
        }

        public void CreateErrorObject()
        {
            IError error;
            if (FileNotFoundException) // put your check here
            {
                error = new ErrorTypeA
                    {
                        Name = ""
                    };
            }
            elseif (InValidOpertionException) // put your check here
            {
                error = new ErrorTypeB
                {
                    Name = "",
                    line = 1
                };
            }
        }

希望这有助于