方法覆盖或拦截

时间:2014-01-04 23:31:47

标签: c# dll methods override intercept

在我的项目中,我引用了许多DLL程序集。其中一个DLL包含我想要更改的bool方法。我没有DLL的原始源,使用Reflector反编译项目似乎不切实际。我想要做的就是拦截或覆盖这个方法或方法调用,这样我就可以改变它的返回值,以匹配我在DLL之外的方法。

有这样的方法吗?谢谢!

编辑:

以下是一个例子:

public virtual bool isOwner()
{
    return false;
}

基本上,我只想更改getOwner以返回true;

4 个答案:

答案 0 :(得分:2)

如果该类是公共的并且该方法被标记为虚拟,那么您可以使用以下语法覆盖它:

public MyClass : TheClass
{
    public override ReturnType MethodName(Arguments)
    {
        //class the base class implementation if needed
        //base.MethodName(Arguments)

        //do your own stuff and return whatever is needed
    }
}

希望这有帮助

编辑:但请注意,这不会取代DLL中的调用代码。只有在您自己实例化派生类并从代码中调用它时,它才会起作用。

答案 1 :(得分:2)

是否有一种通用的方法可以做到你想要的内置.NET?

是的,没有。

如果你想要将X类'方法Y的每次使用都替换为其他代码,那么不,.NET类系统或编译器中没有内置任何代码来实现这一点。

如果您可以继承X类,重写方法Y,然后确保使用类X的所有位置,则使用新类,然后是,这是执行此操作的正确方法。

这很容易做到:

public class YourFixedClass : TheProblematicClass
{
    public override string YourProblematicMethod()
    {
        // probably call the problematic method through base.
        // and fix the return value, or fix the parameters
        // or don't call it at all, re-doing whatever it does
    }
}

或者,如果你可以创建一个实现所有相同接口的新类,包装(委托)原始(有问题)类的所有方法和属性,那么这可能是可行的,但这需要所有实际使用要通过接口的类。

这样:

public class Wrapper : IInterface1, IInterface2
{
    private readonly YourProblematicClass _C;

    public Wrapper(YourProblematicClass c)
    {
        _C = c;
    }

    public string YourProblematicMetho()
    {

        // probably call the problematic method through _C.
        // and fix the return value, or fix the parameters
        // or don't call it at all, re-doing whatever it does
    }
}

另一方面,如果您无法控制调用类/方法的所有代码的位置,那么不,您不能执行任何操作。

那还有什么?好吧,总有调试器接口。你可以创建一个程序,它在某种程度上是自己的调试器,根据需要修补正确的代码,但这可能是非常难以正确的。

简而言之,不,没有办法做你想做的事。你需要找到一种不同的方法来实现这一目标。

您是否考虑过首先更换原始组件?我知道你没有它的源代码,但是因为:

  1. 你丢了它
  2. 你没有成功
  3. 在第1点,我会真的努力通过反编译器或类似方法重新创建源代码,并获得一个新项目来修复它。

    在第2点,你有没有想过联系那些成功的人并向他们寻求帮助?

答案 2 :(得分:1)

嗯,好的,你可以这样做:

public class MyNameClass : MyDllname.MyClassName
{
      public bool isOwner()
      {
           return !base.isOwner();
      }
}

然后你重写了方法,你可以使用MyNameClass

中的istance(如果没有静态)使用DLL中的所有其他方法

答案 3 :(得分:0)

您可以使用“新”修饰符。 请参阅http://msdn.microsoft.com/en-us/library/435f1dw2.aspx

上的示例

或者这个:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(new ClassA().IsEvenDayToday()); // Result: true 
            Console.WriteLine(new ClassB().IsEvenDayToday()); // Result: false

            Console.ReadKey();
        }
    }

    public class ClassA : ClassB
    {
        public new bool IsEvenDayToday()
        {
            return DateTime.Now.Day % 2 == 0;
        }
    }

    public class ClassB
    {
        public bool IsEvenDayToday()
        {
            return DateTime.Now.Day % 2 != 0;
        }
    }