简体   繁体   中英

Conditional Logic to connect generic .Net method arguments

I have a C# method something like:

private static IEnumerable<T2> SomeMethod<T1, T2>(IEnumerable<T1> arg1)
{

}

and I would like to be able to do some conditional logic so that if T1 is A then T2 is B and so on. This is not a problem if I just have those two constraints. However, what if I also wanted logic such as if T1 is C then T2 is D.

The check can be done in the method of course, but a compile time check would be preferable. What I would like is to specify this in the generic where statement of the method.

Is there any way to do this in C# or any other .net language?

For more information T1 is basically a data object and T2 is a specifier that pertains to the T1 data object. All valid T1's are a certain base class while all valid T2's are a different base class. They are two different classes but are always used together. The problem I am trying to avoid is having in the code data and a different specifier which doesn't go with the data passed in together.

It sounds like what you want just isn't expressible in .NET constraints. It sounds like actually you might be better off with simple overloads... but we don't really know enough to say.

If a method is only suitable for a few type arguments - or a few combinations of type arguments - then it might not really be appropriate to be a generic method in the first place.

EDIT: Given this information, it may make more sense:

For more information T1 is basically a data object and T2 is a specifier that pertains to the T1 data object. All valid T1's are a certain base class while all valid T2's are a different base class.

It's not really clear what you mean by a "specifier" here, but it sounds like you might want T2 to be expressed in terms of an interface which relates it to T1. For example, if these are *actually "entity" and "decorator-for-entity" types, you might have:

private static IEnumerable<T2> SomeMethod<T1, T2>(IEnumerable<T1> arg1)
    where T2 : IDecorator<T1>

... where IDecorator<T> is a new interface. Again, there's still not really enough information to say, but this sort of thing can be a valid approach.

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