开发者

How can I define a constructor in an open generic type?

开发者 https://www.devze.com 2023-02-01 13:27 出处:网络
I am trying to create on open gen开发者_如何学Pythoneric type that has a constructor to be used by derived types, but I either don\'t know how to do it or it is not possible -- not sure which.

I am trying to create on open gen开发者_如何学Pythoneric type that has a constructor to be used by derived types, but I either don't know how to do it or it is not possible -- not sure which.

 public struct DataType<T> : IDataType {

    private T myValue;
    private TypeState myState;

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

Any help much appreciated!

Cort

EDIT: the constructor was originally posted as private, which was in error and should have been protected. BUT -- protected is not allowed in a struct, so I changed it to internal.


The constructor doesn't have a generic argument, just like any normal method of the class which can use T but isn't generic either.

public class DataType<T> : IDataType {

    private T myValue;
    private TypeState myState;

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

Note that structs cannot be inherited, and private constructors cannot be called by inheriting classes. Change those two as well in order to get it working.


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

精彩评论

暂无评论...
验证码 换一张
取 消