473,614 Members | 2,342 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can this be done via .net generics? How?

Can this be done via .net generics? How? The % signs below are just to show
how I want to do it, I realise they're not valid syntax.

public abstract class BaseSelectionRe quirement {
...
protected Type mControlType;
protected string mFieldName;
protected Type mFieldType;
protected UserControl mControl;
...

public %mFieldType% Value {
get {
return ( ( %mControlType% ) mControl ).%mFieldName%;
}
set {
( ( %mControlType% ) mControl ).%mFieldName% = value;
}
}
}

So, say my descended class was:

public class HatSelectionReq uirement : BaseSelectionRe quirement {
public HatSelectionReq uirement( ) {
mControlType = HatUserControl;
mFieldType = typeof( Int32 );
mFieldName = "Size";
}
...
}

Then I could get/set the int HatUserControl. Size via
HatSelectionReq uirement.Value
Jul 23 '07 #1
7 1286
Andy Bell wrote:
Can this be done via .net generics? How? The % signs below are just
to show how I want to do it, I realise they're not valid syntax.

public abstract class BaseSelectionRe quirement {
...
protected Type mControlType;
protected string mFieldName;
protected Type mFieldType;
protected UserControl mControl;
...

public %mFieldType% Value {
get {
return ( ( %mControlType% ) mControl ).%mFieldName%;
}
set {
( ( %mControlType% ) mControl ).%mFieldName% = value;
}
}
}

So, say my descended class was:

public class HatSelectionReq uirement : BaseSelectionRe quirement {
public HatSelectionReq uirement( ) {
mControlType = HatUserControl;
mFieldType = typeof( Int32 );
mFieldName = "Size";
}
...
}

Then I could get/set the int HatUserControl. Size via
HatSelectionReq uirement.Value
THat's not the area where generics should be used. Generics should be
used to generalize a piece of algoritmic code by making the containing
class generic. THings like the fieldname aren't producable in generics,
generics is solely about types.

First of all, I'd like to recommend to you to NOT use protected fields
for members. Use private fields and protected properties. This allows
you to obtain the encapsulation that's often needed.

There's another problem with the design: there's a hard reference to
the control the object works on. This is odd to me, wouldn't it be
better to have a class which can work with any object of a given
control type?

I was half-way rewriting your abstract-nonabstract class tandem with a
property descriptor approach when it became really awkward, because:
where is the control instance passed in? If you want to read a value
from a live control, you have to pass it in. In your code that's not
done anywhere so I don't know how you want to do that.

The context of your code is also not very clear, so a good anwser is
abit hard to give.

FB
--
------------------------------------------------------------------------
Lead developer of LLBLGen Pro, the productive O/R mapper for .NET
LLBLGen Pro website: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
Jul 23 '07 #2
Hi Andy,

I suggest you define the BaseSelectionRe quirement class as a generic class.
As for the implementation of the Value property, we don't know either the
field name or its type until at run time. So we need to use reflection to
get/set the field's value at run time.

The following is a sample.

public class BaseClass<mCont rolType,mFieldT ype>
{
protected string mFieldName;
protected UserControl mControl;

public mFieldType Value
{
get
{
PropertyDescrip tor pd =
TypeDescriptor. GetProperties(m Control)[mFieldName];
if (pd != null)
{
return (mFieldType)pd. GetValue(mContr ol);
}
else
{
return default(mFieldT ype);
}

}
set
{
PropertyDescrip tor pd =
TypeDescriptor. GetProperties(m Control)[mFieldName];
if (pd != null)
{
pd.SetValue(mCo ntrol, value);
}
}
}
}
public class DerivedClass:Ba seClass<UserCon trol,Int32>
{
private UserControl uc = new UserControl();
public DerivedClass()
{
this.mFieldName = "Height";
this.mControl = uc;
}

}

Hope this helps.
If you have any question, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support

=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Jul 23 '07 #3
Linda Liu [MSFT] wrote:
Hi Andy,

I suggest you define the BaseSelectionRe quirement class as a generic
class. As for the implementation of the Value property, we don't know
either the field name or its type until at run time. So we need to
use reflection to get/set the field's value at run time.
That is exactly what I needed. It was the PropertyDescrip tor that was
eluding me. Thank you!
Jul 24 '07 #4

"Andy Bell" <an************ @newsgroup.nosp amwrote in message
news:OE******** ******@TK2MSFTN GP03.phx.gbl...
Linda Liu [MSFT] wrote:
>Hi Andy,

I suggest you define the BaseSelectionRe quirement class as a generic
class. As for the implementation of the Value property, we don't know
either the field name or its type until at run time. So we need to
use reflection to get/set the field's value at run time.

That is exactly what I needed. It was the PropertyDescrip tor that was
eluding me. Thank you!
You should get a big performance improvement by defining "open" delegate
types:

mFieldType PropertyGetter< mControlType>(m ControlType that);
void PropertySetter< mControlType>(m ControlType that, mFieldType value);

and instantiating them using Delegate.Create Delegate the results of
PropertyInfo.Ge tGetMethod and PropertyInfo.Ge tSetMethod, respectively, the
first time they are needed. Reflection is slow, if you can manage to avoid
using Invoke then you'll only pay the reflection cost the first time, when
you set up the delegates.

Highly recommended to define methods like:

class MissingAccessor s<T{
static T PropertyNotGett able(object that) { throw new
NotSupportedExc eption(); }
static void PropertyNotSett able(object that, T value) { throw new
NotSupportedExc eption(); }
}

and use these to fill in your delegate members if reflection fails.
Jul 24 '07 #5
Hi Ben,

Thank you very much for your sharing!

I'm interested in your solution, but I couldn't understand it fully.

If possible, could you please give us a complete sample code?

Thank you for your time!

Sincerely,
Linda Liu
Microsoft Online Community Support

Jul 26 '07 #6

"Linda Liu [MSFT]" <v-****@online.mic rosoft.comwrote in message
news:MU******** ******@TK2MSFTN GHUB02.phx.gbl. ..
Hi Ben,

Thank you very much for your sharing!

I'm interested in your solution, but I couldn't understand it fully.

If possible, could you please give us a complete sample code?

Thank you for your time!
Something like this (not compile tested, but at least 99% there):

internal class MissingAccessor s<T{
static T PropertyNotGett able(object that) { throw new
NotSupportedExc eption(); }
static void PropertyNotSett able(object that, T value) { throw new
NotSupportedExc eption(); }
}

public class ArbitraryProper tyProxy<mContro lType, mFieldType>
{
public delegate mFieldType PropertyGetter( mControlType that);
public delegate void PropertySetter( mControlType that, mFieldType
value);

public readonly PropertyGetter getFrom;
public readonly PropertySetter setOnto;

public ArbitraryProper tyProxy(Propert yInfo pi)
{
if (pi.PropertyTyp e != mFieldType) throw new ArgumentExcepti on();
try {
getFrom =
(PropertyGetter )Delegate.Creat eDelegate(typeo f(PropertyGette r),
pi.GetGetMethod ());
}
catch {
getFrom = MissingAccessor s<mFieldType>.P ropertyNotGetta ble;
}
try {
setOnto =
(PropertySetter )Delegate.Creat eDelegate(typeo f(PropertySette r),
pi.GetSetMethod ());
}
catch {
getFrom = MissingAccessor s<mFieldType>.P ropertyNotSetta ble;
}
}
}

public class PropertyLateBin der<mControlTyp e, mFieldType>
{
private readonly static Dictionary<stri ng,
ArbitraryProper tyProxy<mContro lType, mFieldType>cach edProps = new
Dictionary<stri ng, ArbitraryProper tyProxy<mContro lType, mFieldType>>();

public static ArbitraryProper tyProxy<mContro lType, mFieldType>
BindProperty(st ring propName)
{
ArbitraryProper tyProxy<mContro lType, mFieldTypeproxy ;
if (!cachedProps.T ryGetValue(prop Name, out proxy)) {
try {
PropertyInfo pi =
typeof(mControl Type).GetProper ty(propName);
if (pi != null)
proxy = new ArbitraryProper tyProxy<mContro lType,
mFieldType>(pi) ;
}
catch {}
cachedProps[propName] = proxy;
}
return proxy;
}

public static mFieldType Get(mControlTyp e instance, string propName) {
ArbitraryProper tyProxy<mContro lType, mFieldTypeproxy =
BindProperty(pr opName);
if (proxy == null) throw new ArgumentExcepti on("propName") ;
return proxy.getFrom(i nstance);
}

public static void Set(mControlTyp e instance, string propName,
mFieldType newValue) {
ArbitraryProper tyProxy<mContro lType, mFieldTypeproxy =
BindProperty(pr opName);
if (proxy == null) throw new ArgumentExcepti on("propName") ;
proxy.setOnto(i nstance, value);
}
}

void ChangeColor(For m f, Color c, string whichColor) {
foreach (Control c in f.Controls)
PropertyLateBin der<Control, Color>.Set(c, whichColor, c);
}

ChangeColor(thi s, Color.Black, "BackColor" );
ChangeColor(thi s, Color.Red, "ForeColor" );

Imagine that whichColor could be a dropdown list or something like that, so
it's not feasible to do early binding.
Aug 2 '07 #7
Hello Ben,

Thank you very much for your great code!

It will definitly improve the performance. And I think it benefit all of us.

Thank you again for your support of our MSDN managed Newsgroup!

Sincerely,
Linda Liu
Microsoft Online Community Support

Aug 6 '07 #8

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

Similar topics

27
2452
by: Bernardo Heynemann | last post by:
How can I use Generics? How can I use C# 2.0? I already have VS.NET 2003 Enterprise Edition and still can´t use generics... I´m trying to make a generic collection myCollection<vartype> and still no can do... Any info would be great!
2
3097
by: Mr.Tickle | last post by:
So whats the deal here regarding Generics in the 2004 release and templates currently in C++?
23
2536
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics vs C++ templates. Does anyone knows a workaround to do this ? Thx : public class C<T> { private T myValue;
12
2733
by: Michael S | last post by:
Why do people spend so much time writing complex generic types? for fun? to learn? for use? I think of generics like I do about operator overloading. Great to have as a language-feature, as it defines the language more completely. Great to use.
5
2916
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have an "AppleBasket" which is a class that contains a collection of apples. So, some code: class Fruit{ }
11
2487
by: herpers | last post by:
Hello, I probably don't see the obvious, but maybe you can help me out of this mess. The following is my problem: I created two classes NormDistribution and DiscDistribution. Both classes provide an implemation of the operator +. Now I want to write another generic class Plan<DType>, which can
9
5970
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal Experience Only, Please. ...
1
2429
by: Vladimir Shiryaev | last post by:
Hello! Exception handling in generics seems to be a bit inconsistent to me. Imagine, I have "MyOwnException" class derived from "ApplicationException". I also have two classes "ThrowInConstructor" and "ThrowInFoo". First one throws "MyOwnException" in constructor, second one in "Foo()" method. There is a "GenericCatch" generics class able to accept "ThrowInConstructor" and "ThrowInFoo" as type parameter "<T>". There are two methods in...
13
3814
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an application that needs implementations in both Java and C#. I have the Java side done, and it works fantastic, and the C# side is nearly there. The problem I'm running into has to do with the differences in implementations of Generics between the two...
0
8142
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
8640
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
8287
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
8443
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...
0
7114
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5548
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
4058
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
2573
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
0
1438
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.