简体   繁体   中英

Using T as a generic type to a known struct?

Alright, so I have a known struct, which means, I already have members inside this struct... However, I have other structs that I wanna use in 1 function call.

This is the declaration of a function in some class:

public void OpenFile<T, F, U>(ref T body, ref F recordMap, ref U records);

And this is a call for the function in some other class:

OpenFile<SomeStructure1, SomeStructure2, SomeStructure3>(ref someStructureBodyDefinition, ref someStructureRecordMapDefinition, ref someStructureRecordsDefinition);

So, to dump it all down:

Can I use ANY struct for a function call in a generic type and if so, can you show me how to use members of the struct inside the function?

Can I use ANY struct for a function call in a generic type and if so, can you show me how to use members of the struct inside the function?

Okay, based on the edited question it seems you're trying to understand how to use an instance of a parameter of a generic method, where that parameter's type is one of the method's type parameters.

To do that, you need to be able to generalize that type parameter with a constraint. Since we are talking about a value type here (ie struct ), the only such generalization possible would be for the type to implement an interface, and for that interface to be declared on the method as a constraint.

Eg:

interface ISomeInterface
{
    void M1();
    string P1 { get; }
}

struct MyStruct : ISomeInterface { /* ... */ }

void Method<T>(T t) where T : ISomeInterface
{
    // can call M1:
    t.M1();

    // can get property value P1:
    string text = t.P1;
}

If you will be calling this method with different type parameters where the types do in fact implement a common interface, but are not actually declared as such (eg all the structs implement an M1() method, but there is no ISomeInterface and/or some or all of the structs aren't declared as implementing such an interface), then you could use dynamic , either in lieu of making that parameter use a generic type parameter at all, or assigning the passed-in value to a dynamic local variable and using that.

If there is no way to generalize the type being used, then you should rethink whether a generic method is really good design at all. It probably isn't in that scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM