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 15 11216
Try calling GetProperties instead of GetProperty. Then loop through the
returned array and find the property you want.
Thi
Thanks for the quick reply,
I thought about using that but there are several problems. Obviously they
both have the same name, so I have to look at other properties on the
PropertyType attribute to get the right one, however, the candidates for this
would be...
1) Property Type property - I don't know what the return type of the
property is going to be so can't check against that, there are loads of
classes that implement the 'Parent Class', all with different return types.
2) Declaring Type Property - This is the type that the property is declared
in, so if I inherit from ChildClass and don't redefine the Target property,
the declaring type will be ChildClass and not the Type of the object I am
reflecting.
What I need to do, is somehow loop around the class hierarchy and find the
class at the highest (or lowest depending on how you look at it) level that
declares the Target property, but I don't know how without it being messy...
"Truong Hong Thi" wrote: Try calling GetProperties instead of GetProperty. Then loop through the returned array and find the property you want.
Thi
I've ended up doing this... I think it works right, it just looks messy...
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);
System.Reflecti on.PropertyInfo[] oPis = oType.GetProper ties();
System.Reflecti on.PropertyInfo oRequiredPi = null;
int nHierarchyLevel = -1;
foreach(Propert yInfo oPi in oPis)
{
if(oPi.Name=="T arget")
{
//examine the basetypes, counting how many times we go up the hierarchy
int nTempHierarchyL evel = GetHierarchyLev el(oPi.Declarin gType, oType, 0);
if((nTempHierar chyLevel<=nHier archyLevel)||(n HierarchyLevel= =-1))
{
nHierarchyLevel = nTempHierarchyL evel;
oRequiredPi = oPi;
}
}
}
}
private static int GetHierarchyLev el(Type tDeclaringType, Type
tTypeToMatch, int nHierarchyCount )
{
if(tDeclaringTy pe==tTypeToMatc h)
{
return nHierarchyCount ;
}
else
{
nHierarchyCount ++;
return GetHierarchyLev el(tDeclaringTy pe, tTypeToMatch.Ba seType,
nHierarchyCount );
}
}
}
//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
{
}
}
"satankidneypie " wrote: Thanks for the quick reply,
I thought about using that but there are several problems. Obviously they both have the same name, so I have to look at other properties on the PropertyType attribute to get the right one, however, the candidates for this would be...
1) Property Type property - I don't know what the return type of the property is going to be so can't check against that, there are loads of classes that implement the 'Parent Class', all with different return types.
2) Declaring Type Property - This is the type that the property is declared in, so if I inherit from ChildClass and don't redefine the Target property, the declaring type will be ChildClass and not the Type of the object I am reflecting.
What I need to do, is somehow loop around the class hierarchy and find the class at the highest (or lowest depending on how you look at it) level that declares the Target property, but I don't know how without it being messy...
"Truong Hong Thi" wrote:
Try calling GetProperties instead of GetProperty. Then loop through the returned array and find the property you want.
Thi
>2) Declaring Type Property - This is the type that the property is declared in, so if I inherit from ChildClass and don't redefine the Target property, the declaring type will be ChildClass and not the Type of the object I am reflecting.
Does DeclaringType.I sAssignableFrom (typeof(ChildCl ass)) help?
Use the following to only look at the property at the current class scope
(i.e. ChildClass):
System.Reflecti on.PropertyInfo oPi =
typeof(ChildCla ss).GetProperty ("Target",
System.Reflecti on.BindingFlags .DeclaredOnly);
Marc
"satankidneypie " <sa************ @discussions.mi crosoft.com> wrote in message
news:01******** *************** ***********@mic rosoft.com... 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
Seems I put things in wrong order, should be:
typeof(ChildCla ss).IsAssignabl eFrom(property. DeclaringType)
Whoops!
I meant:
System.Reflecti on.BindingFlags .DeclaredOnly |
System.Reflecti on.BindingFlags .GetProperty |
System.Reflecti on.BindingFlags .Public |
System.Reflecti on.BindingFlags .Instance
as the binding flags... I didn't realise at the time because the exception
went away and the code ran to completion... I didn't notice that oPi was
null... it works now, however...
Marc
"Marc Gravell" <mg******@rm.co m> wrote in message
news:Od******** ******@TK2MSFTN GP11.phx.gbl... Use the following to only look at the property at the current class scope (i.e. ChildClass):
System.Reflecti on.PropertyInfo oPi = typeof(ChildCla ss).GetProperty ("Target", System.Reflecti on.BindingFlags .DeclaredOnly);
Marc
"satankidneypie " <sa************ @discussions.mi crosoft.com> wrote in message news:01******** *************** ***********@mic rosoft.com... 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
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
{
}
}
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 {
} } 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: 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...
|
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: 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...
|
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: 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.
| |
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...
| |