recherche

Hi!

I'd like to know if there is any trick to invoke abstract class private instance method

// abstract class


using System;

abstract class MainClass
{
string instanceMethod()
{
return "instanceMethod() in abstract MainClass";
}

static string staticMethod()
{
return "staticMethod() in abstract MainClass";
}

static void Main()
{
// Console.WriteLine(instanceMethod()); //

Console.WriteLine(staticMethod());
}
}

Thanks



Re: Visual C# Language abstract class private instance method

nikov

Code Block

using System;

abstract class MainClass
{
string instanceMethod()
{
return "instanceMethod() in abstract MainClass";
}

static string staticMethod()
{
return "staticMethod() in abstract MainClass";
}

static void Main()
{
MainClass mainClass = new Derived();
Console.WriteLine(mainClass.instanceMethod());

Console.WriteLine(staticMethod());
}
}

class Derived : MainClass { }





Re: Visual C# Language abstract class private instance method

Eugene Dolinskyy

Hi,

You can try using reflection to access it.

Regards,

Eugene






Re: Visual C# Language abstract class private instance method

recherche

Thanks for the reply. Can you give me an example





Re: Visual C# Language abstract class private instance method

Steven Hillaert

Hi,

What you want to do is not really object-orientation, are you sure you're not making a design mistake The whole idea of having private methods is that they are not directly accessible from the outside and instance methods can only be invoked on an instance of the class. Abstract classes are used to be forced to create classes that inherit from it.

So what you want to do is making a hack around these language features or do you want to experiment with reflection


Cheers,
Steven Hillaert

http://blog.hill-it.be




Re: Visual C# Language abstract class private instance method

recherche

Yeah, I'd like to experiment!





Re: Visual C# Language abstract class private instance method

Eugene Dolinskyy

You can use this sample and also visit http://msdn2.microsoft.com/en-us/library/d8ba5k1h.aspx for more information.

Code Block

using System;

using System.Reflection;

using System.Windows.Forms;

public class A

{

private int method()

{

return 0;

}

}

public class B

{

private int method()

{

return 1;

}

}

class Mymethodinfo

{

public static int Main()

{

Console.WriteLine("\nReflection.MethodInfo");

A MyA = new A();

B MyB = new B();

// Get the Type and MethodInfo.

Type MyTypea = Type.GetType("A");

MethodInfo Mymethodinfoa = MyTypea.GetMethod("method");

Type MyTypeb = Type.GetType("B");

MethodInfo Mymethodinfob = MyTypeb.GetMethod("method");

// Get and display the Invoke method.

Console.Write("\nFirst method - " + MyTypea.FullName + " returns " + Mymethodinfoa.Invoke(MyA, null));

Console.Write("\nSecond method - " + MyTypeb.FullName + " returns " + Mymethodinfob.Invoke(MyB, null));

return 0;

}

}

Regards,

Eugene