2014-02-24 62 views
0

我有此功能这是GetPropertyValue,其中I返回一个对象然后一个属性(类型字符串或整数或布尔的)可以接收对象的值。如何从对象接收值到字符串或int或布尔变量而不投射?

public string Name 
    { 
     get { return this.GetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name); } 
     set { this.SetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name, value); } 
    } 

public integer Age 
    { 
     get { return this.GetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name); } 
     set { this.SetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name, value); } 
    } 


public object GetPropertyValue(string sPropertyName) 
    { 

     sPropertyName = sPropertyName.ToLower(); 

     if (mdPropertyBag.ContainsKey(sPropertyName.Replace("get_", ""))) 
     { 
      return mdPropertyBag[sPropertyName.Replace("get_", "")]; 

     } 
     else 
     { 

      return null; 
     } 
    } 

是我收到错误“无法对象隐式转换为字符串”,因为函数返回的对象类型,其中主叫方类型为字符串,整数,布尔等

Get { return this.GetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name); }

+3

你在这里做什么?这是VB代码,而不是C#。你是否试图从C#应用程序调用此代码?另外你在哪里得到错误(哪一行)? – RononDex

+0

在代码中设置一个断点,准确地对失败哪一行工作了,这听起来像你缺少一个ToString – Coops

+0

我复制整个代码到C#,但我无法得到它的工作。我在这里遇到了错误:get {return this.GetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod()。Name); } – shigatsu

回答

2

问题试试这个代码

public string Name 
{ 
    get { return this.GetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name).ToString(); } 
    set { this.SetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name, value); } 
} 

public int Age 
{ 
    get { return (int)this.GetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name); } 
    set { this.SetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name, value); } 
} 


public object GetPropertyValue(string sPropertyName) 
{ 

    sPropertyName = sPropertyName.ToLower(); 

    if (mdPropertyBag.ContainsKey(sPropertyName.Replace("get_", ""))) 
    { 
     return mdPropertyBag[sPropertyName.Replace("get_", "")]; 

    } 
    else 
    { 

     return null; 
    } 
} 
+0

ToString应该是字符串类型,int类型属性怎么样? – shigatsu

+0

看到第二个属性,它将对象值转换为整数 – Jade

+1

@shigatsu'ToString()'适用于所有类型。 –

2

你必须明确地投的objectstringint,因为object是基类。

所以使用下面的代替:

public string Name 
{ 
    get { return this.GetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name).ToString(); } 
    set { this.SetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name, value); } 
} 

public int Age 
{ 
    get { return int.Parse(this.GetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name).ToString()); } 
    set { this.SetPropertyValue(System.Reflection.MethodBase.GetCurrentMethod().Name, value); } 
} 
+0

之后仔细查看Age属性获得者我希望有一种方法不必显式地投射对象。也许一个函数会做。 – shigatsu

相关问题