简体   繁体   English

C#.NET类成员类型基于另一个成员类型

[英]C# .NET Class member type based on another member type

There is a Class define a geometry which includes 2 members, "type", and "coordinates" 有一个类定义一个几何,包括2个成员,“类型”和“坐标”

[DataContract]
public class geometry
{
    [DataMember]
    public string type = "LineString";

    [DataMember]
    public float coordinates;

}

Is there a way that the coordinates member type can be dynamically defined based on the value of "type"? 有没有一种方法可以根据“类型”的值动态定义坐标成员类型? for example, if the "type" is "MultiLineString" the coordinates type will be string? 例如,如果“type”是“MultiLineString”,坐标类型将是字符串?

No, that's not possible. 不,那是不可能的。 The closest you could get is to define a generic class like this: 你可以得到的最接近的是定义一个这样的泛型类:

[DataContract]
public class geometry<T> where T : struct
{
    [DataMember]
    public T coordinates;
}

And then use it like this: 然后像这样使用它:

var geom = new geometry<float>();
geom.coordinates = 1.0f;

If you really want to have the type member there, say, for serialization purposes, you could use something like this: 如果你真的想在那里拥有类型成员,比如说,为了序列化,你可以使用这样的东西:

[DataContract]
public class geometry<T> where T : struct
{
    [DataMember]
    public readonly string type = typeof(T).Name;

    [DataMember]
    public T coordinates;
}

var geom = new geometry<float>();
Console.WriteLine(geom.type); // Single

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM