开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜