C#重写/添加方法/字段对象 [英] C# override/add methods/fields to an object

查看:339
本文介绍了C#重写/添加方法/字段对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建和设置对象我,然后我就可以使用这些对象做的东西的库。



比方说我在给定对象一 A级的



所以我要覆盖一个方法的具体的对象,我不想改变代码的。类,因为这需要更改库



在Ruby的我能做到这一点使用单实例类,如:

 类的Firstclass 
高清测试
P测试


$ b $ =博FirstClass.new

类<< Ø
高清测试
P重写

DEF extraMethod
POK



o.test#打印覆盖
o.extraMethod

现在我该怎么做在C#一样的吗?



更新



我结束了不使用回答我提交因为它太丑陋,它需要改变所有的私人领域在基类要么保护或公众,使他们在派生类中存在,因此我可以从基本的值复制到的。



我最终使用是通过从基类派生到库的类型,并更改库,以便它使用创建实例的方式:

 (A)Activator.CreateInstance(MYTYPE,参数); 


解决方案

C#不(直接)支持运行时间延长类型,不是通过动态机制等。



最接近的选项很可能会使用 ExpandoObject 动态

 动态O =新ExpandoObject(); 
o.a = 10;

o.ExtraMethod =新动作(()=> Console.WriteLine(确定));

//调用
o.ExtraMethod();



话虽这么说,这不是用C#工作的典型方式。


I have a library that creates and setups objects for me, then I can use those objects to do stuff.

Let's say I'm given object "a" of class "A"

So I want to override a method in that specific object, I don't want to change the code of its class because that would require changing the library.

In Ruby I can do that using Singleton Classes, like:

class FirstClass
    def test
        p "test"
    end
end

o = FirstClass.new

class << o
    def test
        p "overridden"
    end
    def extraMethod
        p "ok"
    end
end

o.test # prints "overridden"
o.extraMethod

Now how can I do the same in C#?

Update

I ended up not using the answer I submitted because it's too ugly and it requires changing all private fields in the base class to either protect or public to make them exist in the derived class hence I can copy values from base to derived.

The way I ended up using is to pass a Type derived from the base class to the library and change the library so that it creates instances using:

(A)Activator.CreateInstance(mytype, arguments);

解决方案

C# doesn't (directly) support runtime extension of types, other than via the dynamic mechanisms.

The closest option would likely be to use ExpandoObject with dynamic:

dynamic o = new ExpandoObject();
o.a = 10;

o.ExtraMethod = new Action( () => Console.WriteLine("ok") );

// Invoke
o.ExtraMethod();

That being said, this is not a typical way to work with C#.

这篇关于C#重写/添加方法/字段对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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