【发布时间】:2012-05-01 18:37:45
【问题描述】:
我可以将 ExpandoObject 转换为匿名类型吗?
var anoObj = new { name = "testName", email = "testEmail" };
dynamic expandoObj = new System.Dynamic.ExpandoObject();
// Here I'm populating the expandoObj with same property names/types in anonymoustype(anoObj)
// Now, how to convert this ExpandoObject to anonymoustype ?
var newObj = (typeof(anoObj)expandoObj); // This doesn't work
稍后添加
// 这是我的实体
public class Customer
{
#region Public Properties
[ColumnAttribute(Name = "IdColumn")]
public string Id { get; set; }
[ColumnAttribute(Name = "NameColumn")]
public string Name { get; set; }
[ColumnAttribute(Name = "AddressColumn")]
public string Address { get; set; }
[ColumnAttribute(Name = "EmailColumn")]
public string Email { get; set; }
[ColumnAttribute(Name = "MobileColumn")]
public string Mobile { get; set; }
#endregion
}
// --------------------------------------------- ------------------------------------------
public class LookupService<TEntitySource>
{
public LookupService ()
{
}
public LookupShowable<TEntitySource, TSelection> Select<TSelection>(Expression<Func<TEntitySource, TSelection>> expression)
{
var lookupShowable = new LookupShowable<TEntitySource, TSelection>();
return lookupShowable;
}
}
public class LookupShowable<TEntitySource,TSelection>
{
public LookupShowable()
{
}
public LookupExecutable<TEntitySource, TSelection, TShow> Show<TShow>(Expression<Func<TEntitySource, TShow>> expression)
{
var lookupExecutable = new LookupExecutable<TEntitySource,TSelection,TShow>();
return lookupExecutable;
}
}
public class LookupExecutable<TEntitySource, TSelection, TShow>
{
public TSelection Execute()
{
// Here I want to create a new instance of TSelection and populate values from database and return it.
}
}
//--------------------------------------------- ------------------------------------------
// This is How I want to call this from front end...
var lookupService = new LookupService<Customer>();
var lookupSelection = lookupService.Select(C => new { C.Id, C.Name, C.Mobile }).Show(C => new { C.Id, C.Name}).Execute();
string sID = lookupSelection.Id;
string sName = lookupSelection.Name;
string sMobile = lookupSelection.Mobile;
不要考虑这个中间部分。它的目的是另一个......
我的问题出在 LookupExecutable 类的 Execute() 方法中。我不知道如何创建 TSelection 类型的新实例并为其赋值。此 TSelection 类型始终是匿名类型..
【问题讨论】:
-
你为什么认为你想做你想做的事?
-
我想动态创建一个匿名类型并动态为其赋值。
-
@KushanFernando,但为什么呢?你想用它做什么?
-
这与stackoverflow.com/questions/10240487/…问题有关。但是SO已经关闭了这个问题。如何创建一个始终是匿名类型的泛型类型(TResult)的新实例。以及如何为这个新实例的属性赋值?
-
即使您可以强制转换为匿名类型,它们始终是只读的...请向我们提供更多信息,了解您的整体情况试图完成——而不是你想完成的方式。
标签: c# generics anonymous-types expandoobject