首页 > C# > 我想在字符串中传递类和属性并解析属性的值。GetSourceValue GetSourceValue

我想在字符串中传递类和属性并解析属性的值。GetSourceValue GetSourceValue

上一篇 下一篇

我正在尝试在我的代码中使用反射1 示例实现数据转换。

该函数有一个比较各种类型的开关,但我想删除这些类型和属性,并仅使用单个字符串作为参数来获取属性的值。我想在字符串中传递类和属性并解析属性的值。GetSourceValueGetSourceValue

这可能吗?

分割线

网友回答:

像这样的事情怎么样:

public static Object GetPropValue(this Object obj, String name) {
    foreach (String part in name.Split('.')) {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        PropertyInfo info = type.GetProperty(part);
        if (info == null) { return null; }

        obj = info.GetValue(obj, null);
    }
    return obj;
}

public static T GetPropValue<T>(this Object obj, String name) {
    Object retval = GetPropValue(obj, name);
    if (retval == null) { return default(T); }

    // throws InvalidCastException if types are incompatible
    return (T) retval;
}

这将允许您使用单个字符串下降到属性中,如下所示:

DateTime now = DateTime.Now;
int min = GetPropValue<int>(now, "TimeOfDay.Minutes");
int hrs = now.GetPropValue<int>("TimeOfDay.Hours");

可以将这些方法用作静态方法或扩展。

分割线

网友回答:

 public static object GetPropValue(object src, string propName)
 {
     return src.GetType().GetProperty(propName).GetValue(src, null);
 }

当然,你会想要添加验证等等,但这就是它的要点。

分割线

网友回答:

添加到任何 :Class

public class Foo
{
    public object this[string propertyName]
    {
        get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
        set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
    }

    public string Bar { get; set; }
}

然后,您可以使用:

Foo f = new Foo();
// Set
f["Bar"] = "asdf";
// Get
string s = (string)f["Bar"];

模板简介:该模板名称为【我想在字符串中传递类和属性并解析属性的值。GetSourceValue GetSourceValue】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。

相关搜索
  • 下载密码 lanrenmb
  • 下载次数 295次
  • 使用软件 Sublime/Dreamweaver/HBuilder
  • 文件格式 编程语言
  • 文件大小 暂无信息
  • 上传时间 02-20
  • 作者 网友投稿
  • 肖像权 人物画像及字体仅供参考
栏目分类 更多 >
热门推荐 更多 >
微信公众平台 自适应 微信素材 微信模板 微信文章 html5 响应式 单页式简历模板 企业网站 微信图片
您可能会喜欢的其他模板