当前位置: 首页>>代码示例>>C#>>正文


C# PropertyInfo.SetValue方法代码示例

本文整理汇总了C#中System.Reflection.PropertyInfo.SetValue方法的典型用法代码示例。如果您正苦于以下问题:C# PropertyInfo.SetValue方法的具体用法?C# PropertyInfo.SetValue怎么用?C# PropertyInfo.SetValue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Reflection.PropertyInfo的用法示例。


在下文中一共展示了PropertyInfo.SetValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SetPropertyValue

        // I/F
        public bool SetPropertyValue(object component, PropertyInfo property, string propertyValue)
        {
            var propertyType = property.PropertyType;

            if (propertyType == typeof(string))
            {
                property.SetValue(component, propertyValue, null);
                return true;
            }

            if (propertyType.IsEnum)
            {
                var convertedValue = Enum.Parse(propertyType, propertyValue, true);
                property.SetValue(component, convertedValue, null);
                return true;
            }

            if (typeof(IConvertible).IsAssignableFrom(propertyType))
            {
                var convertedValue = Convert.ChangeType(propertyValue, propertyType, null);
                property.SetValue(component, convertedValue, null);
                return true;
            }

            return false;
        }
开发者ID:willcraftia,项目名称:TestBlocks,代码行数:27,代码来源:DefaultPropertyHandler.cs

示例2: DecodeXmlTextReaderValue

        internal static bool DecodeXmlTextReaderValue(object instance, PropertyInfo propertyInfo, XmlReader xmlTextReader)
        {
            try
            {
                // find related property by name if not provided as parameter
                if (propertyInfo == null)
                    propertyInfo = instance.GetType().GetProperty(xmlTextReader.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                if (propertyInfo == null)
                    return false;
                // unescaped characters <>&
                if (propertyInfo.PropertyType.Equals(typeof(string)))
                    propertyInfo.SetValue(instance, Decode(xmlTextReader.ReadInnerXml().Trim()), null);
                else if (propertyInfo.PropertyType.Equals(typeof(DateTime)))
                    propertyInfo.SetValue(instance, ParseRfc822DateTime(xmlTextReader.ReadInnerXml().Trim()), null);
                else
                    propertyInfo.SetValue(instance, TypeDescriptor.GetConverter(propertyInfo.PropertyType).ConvertFromString(xmlTextReader.ReadInnerXml().Trim()), null);
            }
            catch (Exception e)
            {
                Debug.WriteLine(propertyInfo.Name + ", " + propertyInfo.PropertyType.Name + " / " + instance.ToString() + " " + e.Message);
                return false;
            }
            return true;
        }
开发者ID:miracle091,项目名称:transmission-remote-dotnet,代码行数:25,代码来源:XmlSerializationUtil.cs

示例3: AssingDefaultValue

 public void AssingDefaultValue(PropertyInfo prop)
 {
     var attrib = prop.GetAttribute<SerializePropertyAttribute>();
     if (attrib.CreateNewAsDefaultValue)
         prop.SetValue(this, Activator.CreateInstance(prop.PropertyType), null);
     else if (attrib.DefaultValue != null)
         prop.SetValue(this, attrib.DefaultValue, null);
 }
开发者ID:kkalinowski,项目名称:lib12,代码行数:8,代码来源:SerializableViewModel.cs

示例4: SetPropertyValue

 void SetPropertyValue(NameValueCollection config, PropertyInfo propertyInfo) {
     if (!(string.IsNullOrEmpty(config[propertyInfo.Name.MakeFirstCharLower()]))) {
         propertyInfo.SetValue(this, XpandReflectionHelper.ChangeType(config[propertyInfo.Name.MakeFirstCharLower()], propertyInfo.PropertyType), null);
     } else {
         var defaultValueAttribute = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true).OfType<DefaultValueAttribute>().FirstOrDefault();
         if (defaultValueAttribute != null)
             propertyInfo.SetValue(this, defaultValueAttribute.Value, null);
     }
 }
开发者ID:aries544,项目名称:eXpand,代码行数:9,代码来源:FilterProviderBase.cs

示例5: CopyPropertyValueByInfo

		/// <summary>
		/// Copies value from one property to another
		/// </summary>
		/// <param name="aFromObj">
		/// Source object <see cref="System.Object"/>
		/// </param>
		/// <param name="aFrom">
		/// Source property <see cref="PropertyInfo"/>
		/// </param>
		/// <param name="aToObj">
		/// Destination object <see cref="System.Object"/>
		/// </param>
		/// <param name="aTo">
		/// Destination property <see cref="PropertyInfo"/>
		/// </param>
		/// <returns>
		/// true if successful <see cref="System.Boolean"/>
		/// </returns>
		public static bool CopyPropertyValueByInfo (object aFromObj, PropertyInfo aFrom, object aToObj, PropertyInfo aTo)
		{
			bool res = false;
			if ((aFrom == null) || (aTo == null) || (aFromObj == null) || (aToObj == null)) {
				Debug.Warning ("CopyPropertyValueByInfo", "One is null" + (aFrom == null) + (aTo == null) + (aFromObj == null) + (aToObj == null));
				return (false);
			}
			if (aFrom.CanRead == false)
				throw new ExceptionGettingWriteOnlyProperty();
			object val = aFrom.GetValue (aFromObj, null);
			if (val == null)
				return (false);
				
			if (aTo.CanWrite == false)
				throw new ExceptionAssigningReadOnlyProperty();
			try {
				object no = System.Convert.ChangeType (val, aTo.PropertyType);
				if (no is IComparable) {
					object cval = aTo.GetValue (aToObj, null);
					if ((cval as IComparable).CompareTo(no) != 0) {
						aTo.SetValue (aToObj, no, null);
						res = true;
					}
				}
				else {
					res = true;
					aTo.SetValue (aToObj, no, null);
				}
				no = null;
			}
			catch (System.InvalidCastException) { 
				res = false;
				throw new ExceptionPropertyTranslationError();
			}
			catch (System.ArgumentNullException) {
				res = false;
				throw new ExceptionPropertyTranslationError();
			}
			catch (System.FormatException) {
				res = false;
				throw new ExceptionPropertyTranslationError();
			}
			catch (System.OverflowException) {
				res = false;
				throw new ExceptionPropertyTranslationError();
			}
			
			val = null;
			return (res);
		}
开发者ID:QualitySolution,项目名称:Gtk.DataBindings,代码行数:68,代码来源:ConnectionProvider.cs

示例6: SetOption

        private static bool SetOption(
            object commandLine, PropertyInfo property,
            string[] optionParts, ref string errorMessage)
        {
            bool success;

            if(property.PropertyType == typeof(bool))
            {
                // Last parameters for handling indexers
                property.SetValue(
                    commandLine, true, null);
                success = true;
            }
            else
            {

                if((optionParts.Length < 2)
                    || optionParts[1] == ""
                    || optionParts[1] == ":")
                {
                    // No setting was provided for the switch.
                    success = false;
                    errorMessage = string.Format(
                        "You must specify the value for the {0} option.",
                        property.Name);
                }
                else if(
                    property.PropertyType == typeof(string))
                {
                    property.SetValue(
                        commandLine, optionParts[1], null);
                    success = true;
                }
                else if(property.PropertyType.IsEnum)
                {
                    success = TryParseEnumSwitch(
                        commandLine, optionParts,
                        property, ref errorMessage);
                }
                else
                {
                    success = false;
                    errorMessage = string.Format(
                        "Data type '{0}' on {1} is not supported.",
                        property.PropertyType.ToString(),
                        commandLine.GetType().ToString());
                }
            }
            return success;
        }
开发者ID:rubycoder,项目名称:EssentialCSharp,代码行数:50,代码来源:Listing17.16.UpdatingCommandLineHandler.TryParseToHandleAliases.cs

示例7: Map

        public bool Map(object destinationObject, PropertyInfo destinationProperty, XmlElement element, XmlElement allConfig, ConfigMapper mapper)
        {
            var childElement = element.GetElementNamed(ElementName ?? destinationProperty.Name);

            if (childElement == null)
            {
                return false;
            }

            var elementValue = childElement.InnerText;

            var destinationPropertyType = destinationProperty.PropertyType;

            if (destinationPropertyType.IsEnum)
            {
                var value = Enum.Parse(destinationPropertyType, elementValue);
                destinationProperty.SetValue(destinationObject, value, null);
                return true;
            }

            if (destinationPropertyType.IsNullable())
            {
                if (elementValue == "")
                {
                    destinationProperty.SetValue(destinationObject, null, null);
                    return true;
                }

                destinationPropertyType = destinationPropertyType.GetGenericArguments()[0];
            }

            if (destinationPropertyType.IsA<IConvertible>())
            {
                var value = Convert.ChangeType(elementValue, destinationPropertyType);
                destinationProperty.SetValue(destinationObject, value, null);
                return true;
            }

            var converter = TypeDescriptor.GetConverter(destinationPropertyType);

            if (converter.CanConvertFrom(typeof (string)))
            {
                var value = converter.ConvertFromString(elementValue);
                destinationProperty.SetValue(destinationObject, value, null);
                return true;
            }

            return false;
        }
开发者ID:bushadam,项目名称:simple-config,代码行数:49,代码来源:ElementValueAttribute.cs

示例8: SetValue

 public static void SetValue(this object self, PropertyInfo info, object value)
 {
     if (info != null)
     {
         info.SetValue(self, ChangeType(info, value));
     }
 }
开发者ID:ernestjohn,项目名称:azure-search-util,代码行数:7,代码来源:PropertyExtensions.cs

示例9: SpecifyUtcKind

        private static void SpecifyUtcKind(PropertyInfo property, object value)
        {
            //Get the datetime value
            var datetime = property.GetValue(value, null);

            //set DateTimeKind to Utc
            if (property.PropertyType == typeof(DateTime))
            {
                datetime = DateTime.SpecifyKind((DateTime)datetime, DateTimeKind.Utc);
            }
            else if (property.PropertyType == typeof(DateTime?))
            {
                var nullable = (DateTime?)datetime;
                if (!nullable.HasValue)
                    return;
                datetime = (DateTime?)DateTime.SpecifyKind(nullable.Value, DateTimeKind.Utc);
            }
            else
            {
                return;
            }

            //And set the Utc DateTime value
            property.SetValue(value, datetime, null);
        }
开发者ID:nandusharma,项目名称:tasklist,代码行数:25,代码来源:DbContextExtension-Timezone.cs

示例10: DoAction

 public void DoAction(object siteObject, PropertyInfo propertyInfo, DataGenerator dataGenerator)
 {
     if (propertyInfo.CanWrite)
     {
         propertyInfo.SetValue(siteObject, Guid.NewGuid().ToString(), null);
     }
 }
开发者ID:ManginAlexander,项目名称:mic.comQuestionary,代码行数:7,代码来源:DataGenerator.cs

示例11: ReadBoolean

 public void ReadBoolean(PropertyInfo property)
 {
     XElement booleanElement = this.m_Document.Element(property.Name);
     if (booleanElement != null)
     {
         int value = Convert.ToInt32(booleanElement.Value);
         if (value == 1)
         {
             property.SetValue(this.m_ObjectToWriteTo, true, null);
         }
         else
         {
             property.SetValue(this.m_ObjectToWriteTo, false, null);
         }
     }
 }
开发者ID:WilliamCopland,项目名称:YPILIS,代码行数:16,代码来源:XmlPropertyWriter.cs

示例12: SetValue

        /// <summary>
        /// Sets the new value for a specific property on an object.
        /// </summary>
        /// <param name="instance">Target object to set the property. In most cases this will be a domain object.</param>
        /// <param name="pi">Property info for the property to set.</param>
        /// <param name="newvalue">Value for the property.</param>
        /// <param name="culture"></param>
        /// <exception cref="System.InvalidCastException">Unable to convert the new value to the specified property. </exception>
        /// <exception cref="System.ArgumentNullException">null reference is not accept as a valid argument.</exception>           
        public void SetValue(object instance, PropertyInfo pi, object newvalue, CultureInfo culture = null)
        {
            // else try to cast the new value to the correct type
            object o = Convert.ChangeType(newvalue, pi.PropertyType, culture ?? CultureInfo.CurrentCulture);

            if (pi.CanWrite) pi.SetValue(instance, o, null);
        }
开发者ID:erwinbovendeur,项目名称:ADF,代码行数:16,代码来源:DefaultPropertyParser.cs

示例13: SetPropertyToUniqueValue

 public static void SetPropertyToUniqueValue(this object target, PropertyInfo property, object ensureDifferentFrom)
 {
     object otherValue = null;
     if (ensureDifferentFrom != null)
         otherValue = property.GetValue(ensureDifferentFrom);
     property.SetValue(target, CreateUniqueValueOf(property.PropertyType, otherValue));
 }
开发者ID:rickeygalloway,项目名称:Test,代码行数:7,代码来源:ObjectExtensions.cs

示例14: BindNamed

        void BindNamed(object commando, PropertyInfo property, List<CommandLineParameter> parameters, NamedArgumentAttribute attribute, BindingContext context)
        {
            var name = attribute.Name;
            var shortHand = attribute.ShortHand;
            var parameter = parameters.Where(p => p is NamedCommandLineParameter)
                .Cast<NamedCommandLineParameter>()
                .SingleOrDefault(p => p.Name == name || p.Name == shortHand);

            var value = parameter != null
                            ? Mutate(parameter, property)
                            : attribute.Default != null
                                  ? Mutate(attribute.Default, property)
                                  : null;

            if (value == null)
            {
                context.Report.PropertiesNotBound.Add(property);

                if (!attribute.Required) return;

                throw Ex("Could not find parameter matching required parameter named {0}", name);
            }

            property.SetValue(commando, value, null);

            context.Report.PropertiesBound.Add(property);
        }
开发者ID:rebus-org,项目名称:GoCommando,代码行数:27,代码来源:Binder.cs

示例15: SetValueFor

        public void SetValueFor(Object instance, string key, PropertyInfo property)
        {
            if (Scope.Inputs[key] == null) return;

            object results = ConversionUtil.ConvertTo(property.PropertyType, Scope.Inputs[key]);
            if (results != null) property.SetValue(instance, results, null);
        }
开发者ID:nkmajeti,项目名称:rhino-tools,代码行数:7,代码来源:IInjectedMemberStrategy.cs


注:本文中的System.Reflection.PropertyInfo.SetValue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。