csharp 从继承类型转换为特定类型

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 从继承类型转换为特定类型相关的知识,希望对你有一定的参考价值。

		
		//Example from Micrsofot.Xrm.Sdk
		public T ToEntity<T>() where T : Entity
		{
			if (typeof(T) == typeof(Entity))
			{
				Entity entity = new Entity();
				this.ShallowCopyTo(entity);
				return entity as T;
			}
			if (string.IsNullOrWhiteSpace(this._logicalName))
			{
				throw new NotSupportedException("LogicalName must be set before calling ToEntity()");
			}
			string text = null;
			object[] customAttributes = typeof(T).GetCustomAttributes(typeof(EntityLogicalNameAttribute), true);
			if (customAttributes != null)
			{
				object[] array = customAttributes;
				int num = 0;
				if (num < array.Length)
				{
					EntityLogicalNameAttribute entityLogicalNameAttribute = (EntityLogicalNameAttribute)array[num];
					text = entityLogicalNameAttribute.LogicalName;
				}
			}
			if (string.IsNullOrWhiteSpace(text))
			{
				throw new NotSupportedException("Cannot convert to type that is does not have EntityLogicalNameAttribute");
			}
			if (this._logicalName != text)
			{
				throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Cannot convert entity {0} to {1}", new object[]
				{
					this._logicalName,
					text
				}));
			}
			T t = (T)((object)Activator.CreateInstance(typeof(T)));
			this.ShallowCopyTo(t);
			return t;
		}
		
				internal void ShallowCopyTo(Entity target)
		{
			if (target != null && target != this)
			{
				target.Id = this.Id;
				target.SetLogicalNameInternal(this.LogicalName);
				target.SetEntityStateInternal(this.EntityState);
				target.SetRelatedEntitiesInternal(this.RelatedEntities);
				target.Attributes = this.Attributes;
				target.FormattedValues = this.FormattedValues;
				target.ExtensionData = this.ExtensionData;
				target.RowVersion = this.RowVersion;
				target.KeyAttributes = this.KeyAttributes;
			}
		}

以上是关于csharp 从继承类型转换为特定类型的主要内容,如果未能解决你的问题,请参考以下文章

csharp 将jsonarray / jarray转换为对象类型

csharp NHibernate QueryOver.List扩展支持转换为匿名类型

将继承的属性类型指定为特定子项

如何加载 JSON 文件并将其转换为特定类型的对象?

从扩展 Typegoose 并包含静态类型特定方法的父类继承

Part7 继承与派生 7.3基类与派生类类型转换