由于某些标志,如何在一个模型类中定义不同的属性

本文关键字:模型 一个 定义 属性 标志 于某些 | 更新日期: 2023-09-27 18:17:52

我只是想定义一些东西:

public class MyModel
{
  public int Prop1 {get; set;}
  // pseudocode
  // 
  if(someFlag)
  {
     public Instance1.TypeThatIsDifferentInDifferentInstances Prop2 {get; set;}
  }else
  {
     public Instance2.TypeThatIsDifferentInDifferentInstances Prop2 {get; set;}
  }
}

有可能吗?

由于某些标志,如何在一个模型类中定义不同的属性

public class GenericClass<T>
{
    // T used in constructor.
    public GenericClass(T t)
    {
        data = t;
    }
    // T as private member data type.
    private T data;
    // T as return type of property.
    public T Data  
    {
        get { return data; }
        set { data = value; }
    }
}

你可以这样做:

public class MyModel
{
    public int Prop1 { get; set; }
    public bool Flag { get; set; }
    public object Prop2
    {
        get
        {
            if (Flag)
            {
                return Instance1.TypeThatIsDifferentInDifferentInstances;
            }
            else
            {
                return Instance2.TypeThatIsDifferentInDifferentInstances;
            }
        }
    }
}
public static class Instance1
{
    public static int TypeThatIsDifferentInDifferentInstances = 1;
}
public static class Instance2
{
    public static string TypeThatIsDifferentInDifferentInstances = "testString";
}