Hi,
I'm going to start this off with some code as it'll make it easier to
explain afterwards...
using System;
namespace ConsoleApplicat ion1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
[STAThread]
static void Main(string[] args)
{
//throws an AmbiguousMatchE xception
System.Reflecti on.PropertyInfo oPi =
typeof(ChildCla ss).GetProperty ("Target");
}
}
//Parent Class
class ParentClass
{
public virtual object Target
{
get{return new object();}
}
}
//Child class which inherits from Parent class and hides inherited member
Target with the new keyword, and also changes the return type
class ChildClass : ParentClass
{
public new string Target
{
get{return "";}
}
}
}
What I am trying to do is get the property Target from the ChildClass. When
I do the GetProperty I am returned two PropertyInfo objects matching Target -
one from ParentClass and one from ChildClass. This happens because I am
changing the return type of Target from object to string in the ChildClass.
If the return type stays the same then only one PropertyInfo is returned.
Unfortunately, it's not an option for me to make the return types the same.
It's code written by someone else in a fairly big system and would likely
cause all sorts of problems. Has anyone got any suggestions how I can just
get the Target PropertyInfo from the ChildClass?
It's not feasible to use the declaring type attribute of property info as
there are many other classes in my real world code between ChildClass and
ParentClass that I haven't added to the example above.
I've also taken a look at the BindingFlags attribute parameter, but there is
no suitable BindingFlag that will return me the very top level Target object
- the closest is BindingFlags.De claredOnly, but this won't return me the
Target if I then inherit from ChildClass but then don't override the Target
object.
I hope I have explained this well, it's kinda difficult to get your head
round.
Any help would be much appreciated.
Stu
Dec 1 '05
15 11217
of course I mean while(type!=nul l && pi==null)
(time to get either some sleep or coffee... I guess it'll be the coffee...)
Marc
"Marc Gravell" <mg******@rm.co m> wrote in message
news:Oy******** *****@TK2MSFTNG P15.phx.gbl... You are right - sorry, I looked more at the code you provided than the problem statement (my bad).
How about something like the following (written outside of the IDE, so no guarantee it will compile, but you get the idea)
Type type = typeof(Whatever ); PropertyInfo pi = null; while(type!=nul l && pi!=null) { pi = type.GetPropert y(); // params omitted for brevity, using DeclaredOnly type = type.BaseType; } // pi is now either null or the "highest" version of the property
No idea if it would be quicker or not, but at least it is fairly obvious what it is doing...
Marc
"satankidneypie " <sa************ @discussions.mi crosoft.com> wrote in message news:1D******** *************** ***********@mic rosoft.com... Hi Marc,
If you then inherit from ChildClass with SubChildClass, but don't override 'Target', then Poperty info will be null (Example below)... I have classes that do this too to contend with... (I am still doing it with the way I said in one of my postings above - my third posting down I think)
This code returns null for the property info :
using System; using System.Reflecti on;
namespace ConsoleApplicat ion1 { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { [STAThread] static void Main(string[] args) { //throws an AmbiguousMatchE xception Type oType = typeof(SubChild Class); PropertyInfo oPi = oType.GetProper ty("Target", BindingFlags.De claredOnly | BindingFlags.Ge tProperty | BindingFlags.Pu blic | BindingFlags.In stance); } }
//Parent Class class ParentClass { public virtual object Target { get{return new object();} } }
//Child class which inherits from Parent class and hides inherited member Target, and also changes the return type class ChildClass : ParentClass { public new string Target { get{return "";} } }
//Child class which inherits from Parent class and hides inherited member Target, and also changes the return type class SubChildClass : ChildClass {
} }
>I am still doing it with the way I said in one of my postings above - my third posting down I think
Have you tried Type.IsAssignab leFrom as I suggested? It is much simpler
than the way you do with GetHierarchyLev el.
// Determine if typeToCheck is type1 or a subclass of type1
private bool IsSelfOrChild(T ype type1, Type typeToCheck)
{
return type1.IsAssigna bleFrom(typeToC heck) ;
}
Thi
If I understand the original question correctly (which, admittedly, I didn't
at first), this is more an issue of getting the highest-level version of a
property on aclass-hierarchy (where multiple of the same name may exist via
the new operator, and the top-most class may not define it itself at all).
Given this, I'm not sure that IsAssignableFro m helps much; if it was a case
of getting the correctly typed version, then this can be done using one of
the overloads of GetProperty (that accepts a Type to represent the declared
typ).
Marc
"Truong Hong Thi" <th*****@gmail. com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. . I am still doing it with the way I said in one of my postings above - my third posting down I think Have you tried Type.IsAssignab leFrom as I suggested? It is much simpler than the way you do with GetHierarchyLev el. // Determine if typeToCheck is type1 or a subclass of type1 private bool IsSelfOrChild(T ype type1, Type typeToCheck) { return type1.IsAssigna bleFrom(typeToC heck) ; }
Thi
As I understand, what the OP wanted is that:
- if call with ChildClass, get the Target property as defined in
ChildClass
- if call with SubChildClass and SubChildClass does not override
Target, get the Target property as defined in ChildClass
- if call with SubChildClass and SubChildClass overrides Target, get
the Target property as defined in SubChildClass
- Never get the Target property defined in ParentClass (which
ChildClass extends).
Thus, he could write it as simple as this:
PropertyInfo GetTargetProper ty(Type t)
{
if (typeof(ChildCl ass).IsAssignab leFrom(t))
{
// not ChildClass or one of its children
return null;
}
return t.GetProperty(" Target");
}
Because the original poster decide to get all properties, and walk the
hierachy to see if a class is a child of other class, he can also
obtain that by simply call IsAssgnableFrom .
Thi
Sorry, I forget to put "!" in the first if, and wrongly called
GetProperty instead of GetProperties as I suggested in my first reply.
Here is the updated version. I should work.
I tested in my machine.
PropertyInfo GetTargetProper ty(Type t)
{
if (!typeof(Type1) .IsAssignableFr om(t))
{
// not ChildClass or one of its children
return null;
}
PropertyInfo[] ps = t.GetProperties ();
foreach (PropertyInfo p in ps)
{
if (p.Name == "Target" && p.PropertyType == typeof(string))
{
return p;
}
}
// not found, return nul
return null;
}
Thi This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Steve |
last post by:
Hello,
I'm encountering an unexpected behavior when using
the "new" modifier in a derived class to hide an inherited
base class property. I use "new" intentionally so I can
change the Type of the property in the derived class, and
I can use the derived class as expected through standard
instantiation. The unexpected behavior occurs when I try
to set gather the PropertyInfo for the derived class
property via Reflection. I get an...
|
by: Laser Lu |
last post by:
HI, all,
I just want to invoke an internal method named 'ResolveClientUrl', which
is defined in class System.Web.UI.Control, using an instance object of a
type that derives from Control.
Let's see the following code snippet (class MyControl is a sub class that
derives directly from System.Web.UI.Control):
//...
MyControl instance = new MyControl();
Type type = instance.GetType();
|
by: Nicolas |
last post by:
The lat part is not working why ????????
Please help.........
using System;
namespace ConsoleApplication4
{
|
by: Aaron Queenan |
last post by:
Given the classes:
class Class
{
public static implicit operator int(Class c)
{
return 0;
}
}
class Holder
|
by: John Wright |
last post by:
I have the following code that creates a new appDomain and loads an exe
using reflection. The problem I have is the exe file I pass in is still
locked by the application. I have showcopyfiles = "true" and specified the
locations for the appDomain to use. The shadowfiles and the original file is
locked when I execute the command tmpAssm = .Load(strApplicationName). Now
if I have shadowcopyfiles on, why would setting the assembly to the...
| |
by: Marc Vangrieken |
last post by:
Hi,
I ran into a strange problem a few days ago; when i execute the code at
the bottom of this message GetCustomAttributes() isn't returning
anything. Although the attributes are there... The code is correct, i
think. Does anyone know what might be causing the problem?
foreach (MethodInfo method in this.GetType().GetMethods())
{
methodSequenceNumber = -1;
|
by: BK |
last post by:
I've used reflection quite a bit to launch forms, it works great,
requires little coding, and allows me to launch forms from a dynamic
menu.
Now I have a need to instantiate any one of several business classes
dynamically, so my natural inclination was to use reflection. The
problem I'm running into is that my business classes require arguments
to be passed in where as the forms did not. Here is an example of
launching a form:
|
by: Nightfall |
last post by:
Dear friends,
consider the following scenario, in Visual Studio 2005 and C#
- I create a ASP.NET web service ("server") with a class MyClass and a
WebMethod SomeMethod()
- I create a client application, using "Add web reference..." and
specifying some web reference name "MyName"
Normally I would do:
|
by: balabaster |
last post by:
Why does this work in C#
class test
{
public double Value
{
get;
set;
}
|
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,...
|
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...
| |
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |