Is possible to constraint a generic type parameter to whatever another generic type parameter accepts?

StackOverflow https://stackoverflow.com/questions/22840624

質問

For example:

class ClassA<TA> where TA: T1, T2, T3, T4 ...
{
}

class ClassB<TB> where TB: whatever ClassA.TA accepts
{
  ClassA<TB> MyA;
}

I don't want to copy ClassA's constraint to ClassB because of SSoT and DRY principles.

役に立ちましたか?

解決

You could do that if it was acceptable for ClassB to be a public inner class of ClassA. It's rather inelegant and ugly.

public class ClassA<T> where T : IDisposable
{
    public ClassA(T thing)
    {
        ThingA = thing;
    }
    public T ThingA { get; set; }
    public class ClassB
    {
        public ClassB(T thing)
        {
            ThingB = thing;
        }
        public T ThingB { get; set; }
    }
}

This lets me use this (horrible) syntax:

var b = new ClassA<Stream>.ClassB(stm);

I think that your better bet is to write the two obvious unit tests that use Type.GetGenericParameterConstraints to ensure that ClassA and ClassB are in sync.

他のヒント

If I was in control of the type definitions then I would use a common interface.

public interface IBase { }

public class T1 : IBase { }
public class T2 : IBase { }

public class ClassA<TA> where TA: IBase { }
public class ClassB<TB> where TB: IBase { }

Otherwise C# does not support preprocessor macros, implicit interfaces, or constraint aliasing, so you will need to copy-paste the constraints.

There is no C# language mechanism that would do this. The best that you could hope for would be that some 3rd party tool could potentially list them out for you, but that of course wouldn't stay up to date with any changes to ClassA.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top