473,748 Members | 10,771 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem using Reflection to Assign Generic Delegates

Hi folks

I have a Generic Value Type and I want to detect when the internal value
changes.

///////////////////////////////
public delegate void ValueTypeValida tionHandler<T>( T oldValue, T newValue);

public struct TestType<T>
{
private T value;

public event ValueTypeValida tionHandler<T> valueChanged;

public ValueType(T value)
{
this.value = value;
valueChanged = null;
}

public T Value
{
get { return value; }
set
{
if(valueChanged != null)
valueChanged(th is.value, value);

this.value = value;
}
}
}
//////////////////////

I want to be able to add TestType<> fields to a containing class and have
the containing class assign a delegate to each of the TestType<> fields
without naming them specifically, in the constructor of the containing
class.

So far I have got this far but I want to know how to attach the delegates to
the events.

/////////////////////////
public ContainingType( )
{
FieldInfo[] fia = GetType().GetFi elds(BindingFla gs.Instance |
BindingFlags.No nPublic);

foreach(FieldIn fo fi in fia)
{
Type ft = fi.FieldType;

object fObj = fi.GetValue(thi s);

// the next line doesn't compile; how do I pass the type of each field into
the
generic parameters ?

((TestType<ft>) fObj).valueChan ged += new
ValueTypeValida tionHandler<ft> (HandleValueCha nged<ft>);
}
////////////////////////////

TIA

Joanna

--
Joanna Carter
Consultant Software Engineer
Nov 16 '05 #1
6 2292
Hi!

How have you declared your HandleValueChan ged method?
"Joanna Carter (TeamB)" wrote:
Hi folks

I have a Generic Value Type and I want to detect when the internal value
changes.

///////////////////////////////
public delegate void ValueTypeValida tionHandler<T>( T oldValue, T newValue);

public struct TestType<T>
{
private T value;

public event ValueTypeValida tionHandler<T> valueChanged;

public ValueType(T value)
{
this.value = value;
valueChanged = null;
}

public T Value
{
get { return value; }
set
{
if(valueChanged != null)
valueChanged(th is.value, value);

this.value = value;
}
}
}
//////////////////////

I want to be able to add TestType<> fields to a containing class and have
the containing class assign a delegate to each of the TestType<> fields
without naming them specifically, in the constructor of the containing
class.

So far I have got this far but I want to know how to attach the delegates to
the events.

/////////////////////////
public ContainingType( )
{
FieldInfo[] fia = GetType().GetFi elds(BindingFla gs.Instance |
BindingFlags.No nPublic);

foreach(FieldIn fo fi in fia)
{
Type ft = fi.FieldType;

object fObj = fi.GetValue(thi s);

// the next line doesn't compile; how do I pass the type of each field into
the
generic parameters ?

((TestType<ft>) fObj).valueChan ged += new
ValueTypeValida tionHandler<ft> (HandleValueCha nged<ft>);
}
////////////////////////////

TIA

Joanna

--
Joanna Carter
Consultant Software Engineer

Nov 16 '05 #2
"robkit" <ro****@discuss ions.microsoft. com> a écrit dans le message de news:
9E************* *************** **...icrosof t.com...
Hi!

How have you declared your HandleValueChan ged method?


Thanks for replying...

private void HandleValueChan ged<T>(T oldValue, T newValue) {...}

Have I made it clear enough what I am trying to do ? Is this something to do
with 'method groups' ?

Joanna

--
Joanna Carter
Consultant Software Engineer
Nov 16 '05 #3
Joanna,
the containing class assign a delegate to each of the TestType<> fields
without naming them specifically


How important is this? It would sure make the code cleaner if you
could just name the fields rather than using Reflection.

If you start using Reflection you pretty much have to do it all the
way, and it gets kind of ugly. I think something like this shuld do it
Debug.Assert(ft .HasGenericArgu ments && ft.GetGenericAr guments().Lengt h
== 1 );
Type typeArgument = ft.GetGenericAr guments()[0];

Type handlerType =
typeof(ValueTyp eValidationHand ler<object>).Ge tGenericTypeDef inition().BindG enericParameter s(
new Type[] {typeArgument} );
Delegate handler = Delegate.Create Delegate( handlerType,
typeof(Containi ngType).GetMeth od("HandleValue Changed",
BindingFlags.In stance|BindingF lags.NonPublic) .BindGenericPar ameters(
typeArguments ) );
ft.GetEvent( "valueChang ed" ).AddEventHandl er( fObj, handler );
But this will only work as expected if you change TestType to a class,
because otherwise you just end up modifying a boxed copy of the field.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #4
"Mattias Sjögren" <ma************ ********@mvps.o rg> a écrit dans le message
de news: #4************* *@tk2msftngp13. phx.gbl...
How important is this? It would sure make the code cleaner if you
could just name the fields rather than using Reflection.
The idea is to have a method called from the base class constructor that
takes care of linking up a delegate in the containing class to the
ValueChanged events in my ValueType fields. Then all that has to be done in
derived classes is to add fields appropriate to the business class required.

In a previous version of this framework I wrote in Delphi, I simply added
the ValueTypes to a HashTable and accessed them by named index; I was just
experimenting with generics and trying to cut down on coding :-)

I could always revert to the standard Observer pattern, but I am trying to
exploit the built-in broadcasting mechanism already provided by multicast
delegates.
If you start using Reflection you pretty much have to do it all the
way, and it gets kind of ugly. I think something like this shuld do it <snip>

I will try this but I think your next comment about boxing may well be the
problem.
But this will only work as expected if you change TestType to a class,
because otherwise you just end up modifying a boxed copy of the field.


Is there no way to unbox the TestType from the object? I thought casting it
to the original type would extract it, but that doesn't seem to work.

Regards

Joanna

--
Joanna Carter
Consultant Software Engineer
Nov 16 '05 #5
Joanna,
The idea is to have a method called from the base class constructor that
takes care of linking up a delegate in the containing class to the
ValueChanged events in my ValueType fields.
Sounds like a potentially dangerous design. By the time the base class
constructor runs, the fields in the derived class may not have been
initialized yet.

Is there no way to unbox the TestType from the object?


Sure, but to unbox you need compile time knowledge of the type you
want to cast too, i.e. if it's a TestType<Foo> or a TestType<Bar>.
Which brings be back to the point that using Reflection here may just
be problematic.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #6
"Mattias Sjögren" <ma************ ********@mvps.o rg> a écrit dans le message
de news: uF************* *@TK2MSFTNGP10. phx.gbl...
Sounds like a potentially dangerous design. By the time the base class
constructor runs, the fields in the derived class may not have been
initialized yet.
You are, of course, right; I am used to being able to call code before the
base constructor in Delphi.
Sure, but to unbox you need compile time knowledge of the type you
want to cast too, i.e. if it's a TestType<Foo> or a TestType<Bar>.
I had read about using unbound generic types and was hoping that that might
have provided an answer :-(
Which brings be back to the point that using Reflection here may just
be problematic.


OK, I'm still trying to adjust from Delphi's RTTI to reflection and finding
out what it can and cannot do.

Joanna

--
Joanna Carter (TeamB)

Consultant Software Engineer
Nov 16 '05 #7

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

Similar topics

1
2136
by: andrew queisser | last post by:
I've been trying to dynamically create a class DevT that's derived from a generic base GenBase<T>. It doesn't seem to work. I'm attaching a code sample below that illustrates the problem. CreateType() fails when the base class is a parametrized class, as in DevT : GenBase<int>. CreateType() works if the base class is not parametrized, even if the base of the base was parametrized, as in DevT : GenBaseInt : GenBase<int>
8
6383
by: Rob R. Ainscough | last post by:
I use a generic Processing form (modal) where I pass it an object and method name and parameters if needed and then use CallbyName to execute the passed in method. What this does for me is lock out user input on the parent form as the Processing form has no input controls until all processing is complete. I was curious if CallByName is a good way to perform this operation?
10
3386
by: =?Utf-8?B?QnJpYW4=?= | last post by:
What is the easiest way to convert primitives to a byte array? I tried the BinaryFormatter serialization but it serializes objects so when I serialized an and int it took 54 bytes instead of 4. I tried something like the following but it won't compile (I admit I use generics a lot but haven't written many so this may be way off): class X<T> { public byte ToByteArray(T val) {
9
3116
by: raylopez99 | last post by:
Hello all— I’m trying to get the below to work and cannot get the format right. It’s from this example: http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx What it is: I’m trying to store multicast delegates in a hash table, and then fire the delegates one of two ways (after registering/ creating the delegates, etc).
0
8989
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
9537
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...
1
9319
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,...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6795
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
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4599
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
3309
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
2
2780
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.