473,385 Members | 1,934 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Type based dispatch

Hi,

In the following code, is there any way to get rid of the method marked
below (that has signature static void Func(Base o))? It seems that the
language should be able to dispatch to the correct function for me
based on the actual type of the object, but I can't figure out how to
write that.

(I'm aware that making Func a virtual member of Base, A, and B would
work, but there are a great many different "Func"s that have a lot more
to do with each other than they do with the types A/B so it doesn't
make very much sense to do it that way.)

Thanks for any suggestions or pointers,
scott

---------------------
using System;
using System.Collections.Generic;

class Base { }
class A : Base { }
class B : Base { }

class Program
{
static void Func(A a)
{
System.Console.WriteLine("in Func for A");
}

static void Func(B b)
{
System.Console.WriteLine("in Func for B");
}

// *** This is the function I want to get rid of ***
static void Func(Base o)
{
if (o is A) { Func((A)o); return; }
if (o is B) { Func((B)o); return; }
throw new Exception("bad type");
}

static void Main(string[] args)
{
List<Base> l = new List<Base>();
l.Add(new A());
l.Add(new B());
foreach (Base o in l)
{
Func(o);
}
}
}
---------------------

Feb 1 '06 #1
4 1791
Scott,
In the following code, is there any way to get rid of the method marked
below (that has signature static void Func(Base o))?


Well, there are several ways to do this. I have implemented only one of
them in the following code. I happened to use reflection in the code
snippet. And I do readily admit that this approach is not for the faint of
heart.

I hope that helps.

Regards,

Randy

====================================

using System;
using System.Collections.Generic;
using System.Text;
namespace InheritanceQuestion
{
class Base
{
public static void Func(Base b)
{
System.Console.WriteLine("in Func for Base");
}
}
class A : Base
{
public static void Func(A a)
{
System.Console.WriteLine("in Func for A");
}
}
class B : Base
{
public static void Func(B b)
{
System.Console.WriteLine("in Func for B");
}
}
class Program
{
static void Main(string[] args)
{
List<Base> l = new List<Base>();
l.Add(new A());
l.Add(new B());
foreach (Base o in l)
{
o.GetType().GetMethod("Func", System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.Public).Invoke(o, new object[] {o});
}
}
}
}
Feb 1 '06 #2

"Scott Graham" <sg*****@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
Hi,

In the following code, is there any way to get rid of the method marked
below (that has signature static void Func(Base o))? It seems that the
language should be able to dispatch to the correct function for me
based on the actual type of the object, but I can't figure out how to
write that.

(I'm aware that making Func a virtual member of Base, A, and B would
work, but there are a great many different "Func"s that have a lot more
to do with each other than they do with the types A/B so it doesn't
make very much sense to do it that way.)


Yes it does - just use polymorphism but make all the Func common stuff
private in the base class. Your polymorphic methods can then just call the
appropriate private base methods.

Feb 1 '06 #3
Hi

Thanks for your reply, that's more or less what I was looking for. It
seems a bit heavy, having to load up all the reflection stuff, but what
can you do I guess.

I'd prefer to have the "Func"s in Program rather than inside a
particular data class (A/B), but presumably I can do that with the same
mechanism and do a bit of searching on the parameter reflection info
and then do something similar to what you wrote.

Thanks for your help,
scott.

Randy A. Ynchausti wrote:
Scott,
In the following code, is there any way to get rid of the method marked
below (that has signature static void Func(Base o))?


Well, there are several ways to do this. I have implemented only one of
them in the following code. I happened to use reflection in the code
snippet. And I do readily admit that this approach is not for the faint of
heart.

I hope that helps.

Regards,

Randy

====================================

using System;
using System.Collections.Generic;
using System.Text;
namespace InheritanceQuestion
{
class Base
{
public static void Func(Base b)
{
System.Console.WriteLine("in Func for Base");
}
}
class A : Base
{
public static void Func(A a)
{
System.Console.WriteLine("in Func for A");
}
}
class B : Base
{
public static void Func(B b)
{
System.Console.WriteLine("in Func for B");
}
}
class Program
{
static void Main(string[] args)
{
List<Base> l = new List<Base>();
l.Add(new A());
l.Add(new B());
foreach (Base o in l)
{
o.GetType().GetMethod("Func", System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.Public).Invoke(o, new object[] {o});
}
}
}
}


Feb 2 '06 #4
For anyone interested, this is the (probably horrendously slow) code I
ended up with.

----------
using System;
using System.Collections.Generic;
using System.Reflection;

class Base { }
class A : Base { }
class B : Base { }

class Program
{
private static void Func(A a)
{
System.Console.WriteLine("in Func for A");
}

private static void Func(B b)
{
System.Console.WriteLine("in Func for B");
}

private static bool DelegateToSearchCriteria(
System.Reflection.MemberInfo objMemberInfo,
object objSearch)
{
if (objMemberInfo.Name.ToString() == objSearch.ToString())
return true;
else
return false;
}

private static Dictionary
<
string,
Dictionary<Type, MethodInfo>
msDispatch

= new Dictionary<string, Dictionary<Type, MethodInfo>>();

private static void MakeDispatchFor(string name)
{
MemberInfo[] arrayMemberInfo = typeof(Program).FindMembers(
System.Reflection.MemberTypes.Method,
System.Reflection.BindingFlags.Static
| System.Reflection.BindingFlags.NonPublic,
new MemberFilter(DelegateToSearchCriteria), name);
foreach (MethodInfo mi in arrayMemberInfo)
{
ParameterInfo[] pi = mi.GetParameters();
if (pi.Length == 1)
{
if (!msDispatch.ContainsKey(name))
{
msDispatch[name] = new Dictionary<Type, MethodInfo>();
}
msDispatch[name][pi[0].ParameterType] = mi;
}
}
}

private static object Call(string name, object o)
{
return msDispatch[name][o.GetType()]
.Invoke(null, new object[] { o });
}

static void Main(string[] args)
{
MakeDispatchFor("Func");

List<Base> l = new List<Base>();
l.Add(new A());
l.Add(new B());
foreach (Base o in l)
{
Call("Func", o);
}
}
}

----------

scott

Feb 5 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Joakim Hove | last post by:
Hello, I wondered how I could test wether an argument was of type compiled regexp: from types import * def do_something(arg): if type(arg) is StringType: print "%s is a string" % arg
0
by: Tim Roberts | last post by:
It looks to me like the handling of the currency type in an ADODB connecction from Python is broken. Currency data in an Access database is stored as a 64-bit integer, scaled by 10000. In an...
3
by: Gernot Frisch | last post by:
er... what I want to know is: template <class T> void foo(void) { switch (typeof(T)) { } } Know what I mean?
2
by: Dave | last post by:
Hello all, I am creating a linked list implementation which will be used in a number of contexts. As a result, I am defining its value node as type (void *). I hope to pass something in to its...
59
by: Michael C | last post by:
eg void DoIt() { int i = FromString("1"); double d = FromString("1.1"); } int FromString(string SomeValue) {
14
by: Joseph Turian | last post by:
How can I determine the type of some particular typename? I am writing a template, and it needs special case handling for some particular types: template <typename T> class foo { public:...
3
by: tyler.schlosser | last post by:
Hi there, I am trying to launch a program called AmiBroker using the command: AB = win32com.client.Dispatch("Broker.Application") However, I have a dual-core CPU and would like to launch two...
11
by: Frederic Rentsch | last post by:
Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? ...
3
by: Tigera | last post by:
Greetings, I too have succumbed to the perhaps foolish urge to write a video game, and I have been struggling with the implementation of multiple dispatch. I read through "More Effective C++"...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.