Problems encountered in C # reflection to Object assignment--type conversion

Source: Internet
Author: User

Assigning values to an object property can be assigned by Propertyinfo.setvalue (), but be aware that the type of the value is consistent with the property.

Creating an Object instance

1>

var obj = Assembly.Load( "AssemblyName" ).CreateInstance( "AssemblyName" + "ClassFullName" );2> var obj = Activator.CreateInstance(ClassType); Assign Value var property = obj.GetType().GetProperty( "PropertyName" ); //此时可以使用GetProperty获取属性数组,循环进行赋值,这里主要讲解类型问题。1> The property type is a known type, for example: int int value=500; property.SetValue(obj,value, null );2> The property type is a known type and the original value is another type. Example: the target type is int and the value is string string value= "500" ; property.SetValue(obj, int .TryParse(value), null ); //类型转换。3> The property type is an unknown non-generic type, the target type is not determined, and the type conversion is done. object value= "500" ; property.SetValue(obj,Convert.ChangeType(value,property.PropertyType), null ); //类型转换。

Problems encountered in C # reflection to Object assignment--type conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.