473,606 Members | 2,171 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Collecti ons.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 1802
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.Collecti ons.Generic;
using System.Text;
namespace InheritanceQues tion
{
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().Get Method("Func", System.Reflecti on.BindingFlags .Static |
System.Reflecti on.BindingFlags .Public).Invoke (o, new object[] {o});
}
}
}
}
Feb 1 '06 #2

"Scott Graham" <sg*****@gmail. com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.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.Collecti ons.Generic;
using System.Text;
namespace InheritanceQues tion
{
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().Get Method("Func", System.Reflecti on.BindingFlags .Static |
System.Reflecti on.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.Collecti ons.Generic;
using System.Reflecti on;

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 DelegateToSearc hCriteria(
System.Reflecti on.MemberInfo objMemberInfo,
object objSearch)
{
if (objMemberInfo. Name.ToString() == objSearch.ToStr ing())
return true;
else
return false;
}

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

= new Dictionary<stri ng, Dictionary<Type , MethodInfo>>();

private static void MakeDispatchFor (string name)
{
MemberInfo[] arrayMemberInfo = typeof(Program) .FindMembers(
System.Reflecti on.MemberTypes. Method,
System.Reflecti on.BindingFlags .Static
| System.Reflecti on.BindingFlags .NonPublic,
new MemberFilter(De legateToSearchC riteria), name);
foreach (MethodInfo mi in arrayMemberInfo )
{
ParameterInfo[] pi = mi.GetParameter s();
if (pi.Length == 1)
{
if (!msDispatch.Co ntainsKey(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
1667
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
1247
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 ADODB recordset, this is returned as a 2-tuple, where the second element is the currency value, but the value is stored as a normal integer, not a lont integer. Thus, it fails for values greater than about $214,700 (2**32 / 10**4). Here is an...
3
5236
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
2430
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 "constructor" so that I will be able to manipulate my list without the need for constant casting; some sort of runtime type-safety mechanism. For example, I want a linked lists of ints. I want to be able to say:
59
3424
by: Michael C | last post by:
eg void DoIt() { int i = FromString("1"); double d = FromString("1.1"); } int FromString(string SomeValue) {
14
2197
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: foo() { if (T == int) cerr << "int\n";
3
6928
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 instances of AmiBroker. I know it is possible to run two instances simultaneously since it is easy to do manually by double-clicking the AmiBroker.exe file twice. However, when I write two lines of code like this:
11
32329
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? class Derived (Base): def __init__ (self, base_object): # ( copy all attributes ) ...
3
3769
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++" by Scott Meyers, and though I am impressed with his implementation, I wanted to find a way to use multiple dispatch in a way that was less complicated. Forgive me if the result, below, has been posted before or written of before - I haven't read...
0
8015
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7951
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8439
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8430
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8094
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
5966
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3930
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2448
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1553
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.