惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Blog of Author Tim Ferriss
S
Securelist
D
Docker
The Register - Security
The Register - Security
GbyAI
GbyAI
Recorded Future
Recorded Future
Engineering at Meta
Engineering at Meta
Stack Overflow Blog
Stack Overflow Blog
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
罗磊的独立博客
博客园 - 【当耐特】
F
Full Disclosure
WordPress大学
WordPress大学
腾讯CDC
小众软件
小众软件
大猫的无限游戏
大猫的无限游戏
D
DataBreaches.Net
SecWiki News
SecWiki News
L
Lohrmann on Cybersecurity
I
InfoQ
MyScale Blog
MyScale Blog
量子位
Cyberwarzone
Cyberwarzone
博客园 - 三生石上(FineUI控件)
The Hacker News
The Hacker News
F
Fortinet All Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Jina AI
Jina AI
博客园_首页
H
Help Net Security
K
Kaspersky official blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Webroot Blog
Webroot Blog
Blog — PlanetScale
Blog — PlanetScale
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
The Cloudflare Blog
P
Proofpoint News Feed
V
Visual Studio Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tailwind CSS Blog
爱范儿
爱范儿
P
Privacy International News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
The GitHub Blog
The GitHub Blog
C
Cybersecurity and Infrastructure Security Agency CISA
B
Blog RSS Feed

博客园 - 东国先生

MongoDB - 安装及相关资料 8种Nosql数据库系统对比 Apache 服务器安装和配置相关资料 ffmpeg: error while loading shared libraries: libavdevice.so.53 亚马逊S3 - The difference between the request time and the current time is too large. Imagick setFont() 不能设置字体问题 当Linux中glibc被无意删除后…… vim终端下中文乱码问题 解决Linux中文乱码 Linux下PHP文件操作提示无权限 还原sql server数据库时,无法获得对数据库的独占访问权 zen-cart开发教程 - 通知者/观察者模式 zen-cart开发教程 - 开发Sidebox插件 修改zen-cart下单和付款流程以防止漏单 【转载】Paypal 标准变量列表 C#中的委托 zen-cart开发教程 - 概述 PHP文件操作函数 2009年终总结
利用反射设置对象的属性(Property)
东国先生 · 2010-03-05 · via 博客园 - 东国先生

对于一个对象,要设置它的某个Property,除了“obj.PropertyName=XXX” 这种方式直接设置的方式,还有哪些方式呢。

  1. 利用Type.InvokeMember()
    如下面的代码

    using System.Reflection;
    MyObject obj 
    = new MyObject();
    obj.GetType().InvokeMember(
    "Name",
        BindingFlags.Instance 
    | BindingFlags.Public | BindingFlags.SetProperty,
        Type.DefaultBinder, obj, 
    "MyName");

    若按这种方式,那么如果对象obj不包含名为Name的属性,或者该属性不可设置(没有set访问器)时,则会抛出异常。


  2. 可以先获取一个该属性的PropertyInfo对象,然后在设置其值。这样你可以检测该属性是否存在,以及该属性是否能进行设置。

    using System.Reflection;
    MyObject obj 
    = new MyObject();
    PropertyInfo prop 
    = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
    if(null != prop && prop.CanWrite)
    {
        prop.SetValue(obj, 
    "MyName"null);
    }

    也许你会想,干嘛不直接使用“obj.PropertyName=XXX”语句来设置值,而要这样大费周折呢。一般情况下这样显得的确多余,但一些特定情况,这样还是很有用处的,例如,在大家都知道的上层架构中,我们需要将数据库中读取出来的内容封装到一个实体对象中,这样就需要写大量的这种赋值语句,这时这种方式的优点就显示出来了。