C# - 在运行时确定属性类型

时间:2009-11-30 18:23:22

标签: c# runtime anonymous

这是我想要做的:

public [type determined at runtime] ImageToShow
{
  get
  {
    if(this.IsWebContext)
    {
       return this.GetString();
    }
    else
    {
       return this.GetBitmap();
    } 
  }
}

首先看看,如果T是创建此类实例的泛型类型,它看似简单易行。但我想要做的是根据在Image属性中做出的决定来提供String或Bitmap,以便在Image属性中包含作为Image的服务器的知识,而其他任何地方都不需要知道它。我当然可以制作返回类型'对象'并且它可以工作,但我不希望拳击和拆箱效率低下我也不想涉及反射。

在我放弃这个想法之前,我只是想和你们一起检查一下这是否可行。

5 个答案:

答案 0 :(得分:2)

调用者使用公共财产“知道”不是更好吗

YourClass.IsWebContext

期待什么?

然后你就可以使用泛型类型T.

答案 1 :(得分:2)

将值类型转换为引用类型时会发生装箱。

int i = 5;

object o = i; // Boxing

由于您只返回StringBitmap这两种引用类型,因此您可以使用对象而无需担心装箱或取消装箱。

答案 2 :(得分:1)

似乎不是解决这个问题,而应该考虑不同的设计。例如,为将要成为WebContext并实现公共接口的所有内容创建一个单独的类。

答案 3 :(得分:1)

首先,将引用类型作为对象返回不是装箱。仅在使用valuetype作为referencetype时才会出现Boxing。

现在假设您正在使用returntype对象。然后,您可以使用is运算符验证返回的对象实例是否属于某种类型。

object o = myClass.ImageToShow;

if (o is String)
{
  // Use as a String
}
else if (o is Bitmap)
{
  // Use as a Bitmap
}

其次,我不建议在每个属性中检查IsWebContext。创建一个基类更有意义,并根据它所使用的环境进行专门化。

答案 4 :(得分:0)

是的,使用界面。

   public interface IAmImage {}
   public class StringImage: IAmImage
   {
      private string img;
      public string Image { get { return img; } set { img = value; } }
      public StringImage(string image) { img = image;}
   }
   public class BitmapImage: IAmImage
   {
      private Bitmap img;
      public Bitmap Image { get { return img; } set { img = value; } }
      public BitmapImage(Bitmap image) { img = image;}
   }

...并在您的客户端代码....

   public IAmImage ImageToShow 
   {  
       get  
       {    
           return this.IsWebContext?
              new StringImage(this.GetString()):        
              new BitmapImage(this.GetBitmap());    
       }
   } 
相关问题