Ich habe eine Schnittstellenfunktion namens setParametersAsync (BaseClass MyObject) , die Schnittstelle ist nicht meine, daher kann ich die Signatur nicht ändern. Jetzt muss ein neuer Typ hinzugefügt werden. Dies ist ein generischer Typ der abgeleiteten Klasse : BaseClass, wobei t: struct < /code> Der Typ t ist hier nicht relevant. Ich möchte dieselben Methoden auf dem abgeleiteten Klassenobjekt für alle Arten von T.
aufrufen.// existing class, can't alter the signature
public class ExampleClass : IParameterMethods
{
// inherited from interface, can't alter the signature
public async Task SetParametersAsync(BaseClass myObject)
{
if (myObject is MyClassA a)
{
a.DoThis();
MethodThatExpectsAMyClassAParameter(a);
}
// ...other ifs
// NOW THIS IS WHAT I NEED TO ADD FOR THE NEW GENERIC CLASS:
else if (myObject is DerivedClass derived)
{
derived.MethodFromGenericClass();
MethodThatExpectsDerivedClassTParameter(derived);
}
}
// this is a method I need to call with my generic object, as you can see the exact type of T does not matter, it just has to be a struct type that's all
private void MethodThatExpectsDerivedClassTParameter(DerivedClass derived) where T: struct
{
...
}
< /code>
Natürlich nicht kompiliert, weil T nicht bekannt ist. Ich möchte nicht "ifs" für alle möglichen Arten von T hinzufügen. Was kann ich also tun, um dieses Problem zu lösen?
Objekt an mygenericype , wenn type t nicht wichtig ist ⇐ C#
-
- Similar Topics
- Replies
- Views
- Last post