public class A
{
public string PropA { get; set; }
}
public class Aplus : A
{
public string PropAplus { get; set; }
}
A objA = new A() { PropA = "irgendwas" };Aplus objAplus = objA as Aplus;
objAPlus = null;
|
News:
|
|
Edit: Tags bearbeitet
– Floyd 01.04.2011
|
A objA = new Aplus() { PropA = "irgendwas" };public class A
{
public string PropA { get; set; }
}
public class Aplus : A
{
public string PropA { get; set; }
}
public class Aplus2 : A
{
public string PropA { get; set; }
}
public partial class MainForm : Form
{
A _obj1;
A _obj2;
public void SomeInteraction()
{
_obj1 = new Aplus() { propA = "Some Value" };
_obj2 = new Aplus2() { propA = "Some Value" };
}
}
|
|
|
Ich wollte ein DO, das ich über eine ServiceSchnittstelle erhalten, bequem um weitere Properties erweitern. Aber ich bekomme das Objekt ersteinmal als objA ...
Danke für dein Angebot – Baumgärtel 01.04.2011
|
später habe ich ein Objekt der Klasse A:
A objA = new A() { PropA = "irgendwas" };
nun mein Problem (wohl eher meine gedankliche Blockade): wie bekomme ich objA zu einem objAplus?
Aplus objAplus = objA as Aplus;
bringt zur Laufzeit:
objAPlus = null;
A objA = new A();
Aplus objAplus = objA as Aplus; // = null
Aplus objAplus = new Aplus();
A objA = objAplus as A; // = A
Aplus objAplus2 = objA as Aplus // = Aplus
A objA = new A() { PropAplus = "irgendwas" };
Aplus objAplus = objA.PropAplus as Aplus; // funktioniert = Aplus|
|
|
Stimmt, hätte hilfreich sein können, wenn ich geschrieben hätte, was ich will ... :-)
Ich bekomme über eine Serviceschnittstelle ein DatenObjekt. Dieses möchte ich um eigene Properties erweitern, ggf. sogar 'ne kleine Methode dazu, und dann als ObservableCollection in einem Grid anzeigen lassen. Wollte mir Arbeit bei der Anlage und bei Änderungen ersparen, bin halt doch nur ein typischer Entwickler ;-) Aber eigentlich war mein Problem, dass ich nicht wußte, in welcher Richtung ich casten kann ... aber es schon jetzt logisch. Danke allen – Baumgärtel 01.04.2011
|
|
|
using System.Reflection;
public class A
{
public string PropA { get; set; }
}
public class Aplus : A
{
public Aplus(A a){
Type typeA = a.GetType();
while (typeA != null)
{
FieldInfo[] myObjectFields = typeA.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
foreach (FieldInfo fi in myObjectFields)
{
fi.SetValue(this, fi.GetValue(a));
}
typeA = typeA.BaseType;
}
}
public string PropAplus { get; set; }
}
public class MyClass
{
public static void RunSnippet()
{
A objA = new A() { PropA = "irgendwas" };
Aplus objAplus = new Aplus(objA);
Console.WriteLine(objAplus.PropA);
}
}
|
|
|
|