Objekt an mygenericype , wenn type t nicht wichtig ist

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Objekt an mygenericype , wenn type t nicht wichtig ist

by Anonymous » 21 Mar 2025, 08:19

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?

Top