1

Hi is there any workaround on creating a class that has both struct and string as a generic constraint?

public class AutoEncryptor<T> where T : struct, string {
{
      private T? _value;

      // codes removed for brevity
}

My goal is to save myself from the hassle of creating duplicate methods with the same structure but the difference is, the other one accepts a string and the other one accepts struct (value types).

4

1 回答 1

4

不,这是不可能的。最好的方法是使用抽象的泛型基类并专门用于stringstruct

public abstract class AutoEncryptorBase<T>
{
    protected T _value;
}

public class AutoEncryptor<T> : AutoEncryptorBase<T?> where T : struct
{
}

public class TextAutoEncryptor : AutoEncryptorBase<string>
{
}
于 2016-12-06T03:04:58.163 回答