How to define a constructor in an open generic type?

I am trying to create on an open generic type that has a constructor that will be used by derived types, but I either don’t know how to do this, or it is impossible - I’m not sure which one.

 public struct DataType<T> : IDataType {

    private T myValue;
    private TypeState myState;

    internal DataType<T>(T initialValue, TypeState state) {
        myValue = initialValue;
        myState = state;
    }
 }

Any help is much appreciated!

Cort

EDIT: The constructor was originally published as private, which was a mistake and should have been protected. BUT - protection is not allowed in the structure, so I changed it to internal.

+3
source share
2 answers

The constructor does not have a common argument, like any normal class method that can use T, but is also not general.

public class DataType<T> : IDataType {

    private T myValue;
    private TypeState myState;

    protected DataType(T initialValue, TypeState state) {
        myValue = initialValue;
        myState = state;
    }
 }

, , . , .

+7
private DataType(T initialValue, TypeState state)
{
     myValue = initialValue;
     myState = state;
} 
0

Source: https://habr.com/ru/post/1781902/


All Articles