我知道我不能写一个像这样的方法:
public var MyMethod()
{
return new{ Property1 = "test", Property2="test"};
}
Run Code Online (Sandbox Code Playgroud)
我可以这样做:
public object MyMethod()
{
return new{ Property1 = "test", Property2="test"}
}
Run Code Online (Sandbox Code Playgroud)
但我不想做第二种选择,因为如果我这样做,我将不得不使用反射.
为什么我要这样做:
今天我在我的aspx页面中有一个方法返回一个数据表作为结果而我无法更改它,我试图将此DataTable转换为具有我想要使用的属性的Anonymous方法.我不想创建一个类只是为了这样做,因为我需要多次执行相同的查询,我想创建一个返回匿名类型的方法将是一个很好的意识形态.
我今天遇到了以下问题,我想知道我的问题是否有解决方案.
我的想法是构建匿名类并将其用作WinForm BindingSource的数据源:
public void Init()
{
var option1 = new
{
Id = TemplateAction.Update,
Option = "Update the Templates",
Description = "Bla bla 1."
};
var option2 = new
{
Id = TemplateAction.Download,
Option = "Download the Templates",
Description = "Bla bla 2."
};
var list = new[] {option1, option2}.ToList();
bsOptions.DataSource = list; // my BindingSource
// cboTemplates is a ComboBox
cboTemplates.DataSource = bsOptions;
cboTemplates.ValueMember = "Id";
cboTemplates.DisplayMember = "Option";
lblInfoTemplates.DataBindings.Add("Text", bsOptions, "Description");
}
Run Code Online (Sandbox Code Playgroud)
到目前为止工作正常.
我遇到的问题是从BindingSource的"Current"属性中获取Id,因为我无法将其强制转换为匿名类型:
private void cmdOK_Click(object …Run Code Online (Sandbox Code Playgroud) 我正在调用一个返回包含ac#Anonymous Type对象的List变量的方法.例如:
List<object> list = new List<object>();
foreach ( Contact c in allContacts ) {
list.Add( new {
ContactID = c.ContactID,
FullName = c.FullName
});
}
return list;
Run Code Online (Sandbox Code Playgroud)
我如何在我正在处理的代码中引用此类型属性,例如
foreach ( object o in list ) {
Console.WriteLine( o.ContactID );
}
Run Code Online (Sandbox Code Playgroud)
我知道我的样本是不可能的,我只是这样说,我需要确切地识别匿名类型的每个属性.
谢谢!
方案:
不只是其中一个答案是正确的和/或建议一个有效的解决方案.我最终使用了Greg选项3的答案.我dynamic在.NET 4.0 中学到了一些非常有趣的东西!
我可以在函数中使用匿名类型作为返回类型,然后将返回值的内容填充到某种数组或集合中,同时还向新数组/集合添加其他字段吗?请原谅我的伪代码......
private var GetRowGroups(string columnName)
{
var groupQuery = from table in _dataSetDataTable.AsEnumerable()
group table by new { column1 = table[columnName] }
into groupedTable
select new
{
groupName = groupedTable.Key.column1,
rowSpan = groupedTable.Count()
};
return groupQuery;
}
private void CreateListofRowGroups()
{
var RowGroupList = new List<????>();
RowGroupList.Add(GetRowGroups("col1"));
RowGroupList.Add(GetRowGroups("col2"));
RowGroupList.Add(GetRowGroups("col3"));
}
Run Code Online (Sandbox Code Playgroud) 我使用两个DataContext对象返回单独的AsQueriable()数据集,然后使用linq连接两个.数据构造工作完美,但是当我将组合数据集传递给视图时,我得到的错误"对象"不包含"名称"的定义.
在调试会话期间,我可以清楚地看到父模型和foreach循环中的每个"项"都具有可见/可访问的所有数据和键.我很困惑.
stackoverflow.com上与此问题相关的许多其他q&a都没有解决我的问题,因此会欣赏一双新的眼睛并希望能够解决这个问题.
非常感谢! - 代码时间:
数据构建
public ActionResult SplashImages()
{
var g = (from i in GetGallerySplash() join o in GetFestivals() on i.Festival equals o.ID orderby i.Rating descending select new {i.Photo, i.OwnedBy, i.Rating, o.Name });
Response.ContentType = "text/xml";
return View(g);
}
private IEnumerable<Gallery> GetGallerySplash()
{
GallerysDataContext gdc = new GallerysDataContext();
return (from i in gdc.Galleries orderby i.Rating descending select i).Take(15).AsQueryable();
}
private IEnumerable<Festival> GetFestivals()
{
FestivalsDataContext fdc = new FestivalsDataContext();
return (from i in fdc.Festivals select i).AsQueryable();
}
Run Code Online (Sandbox Code Playgroud)
VSExpress的错误屏幕: …
我的 API 返回一个object, 填充了匿名类型。我可以GET通过 HTTP 并解析为 json。
但是......我对同一方法的单元测试无法解析匿名类型。
使用 Dotnet 框架 4.7.2。
下面的代码显示了一个项目中
的调用者和另一个项目中的被调用者,
有 2 次不同的失败尝试。第二个是从 SO和这里复制的,没有评论它不起作用。但是……不适合我。
错误信息是:
System.InvalidCastException:无法将
类型为“<>f__AnonymousType1`2[System.String,System.String]”的对象转换
为类型“<>f__AnonymousType0`2[System.String,System.String]”。
在哪里可以看到类型是不同的。
但是 IIRC 前段时间有一个 dotnet 更新解决了这个问题,让它们“平等”。
我试图通过从 dotnet 框架 web api 返回匿名类型来解决用例。
(还有其他解决方案,如动态、反射、类型或更多端点,但这是另一个问题)
请注意,此测试用例不涉及 HTTP,它纯粹是 dotnet 框架问题。
public class MyController: ApiController
{
public object Get(string id)
{
return new { Key = id, Value = "val:" + id };
}
}
Run Code Online (Sandbox Code Playgroud)
[Fact]
public void MyTest
{ …Run Code Online (Sandbox Code Playgroud) 我有一个网格,我正在设置DataSource一个List<IListItem>.我想要的是让列表绑定到底层类型,并显示这些属性,而不是在中定义的属性IListItem.所以:
public interface IListItem
{
string Id;
string Name;
}
public class User : IListItem
{
string Id { get; set; };
string Name { get; set; };
string UserSpecificField { get; set; };
}
public class Location : IListItem
{
string Id { get; set; };
string Name { get; set; };
string LocationSpecificField { get; set; };
}
Run Code Online (Sandbox Code Playgroud)
如何绑定到网格,以便如果我List<IListItem>包含用户,我将看到特定于用户的字段?编辑:请注意,我想绑定到Datagrid的任何给定列表将由单个底层类型组成.
如何遍历Object类型的List?
List<object> countries = new List<object>();
countries.Add(new { Name = "United States", Abbr = "US" , Currency = "$"});
countries.Add(new { Name = "Canada", Abbr = "CA", Currency = "$" });
...more
Run Code Online (Sandbox Code Playgroud)
我想在我的视图中做一些事情(使用属性名称)
@model ViewModel
@foreach(object country in Model.Countries)
{
Name = country.Name
Code = country.Abbr
Currency = country.Currency
}
Run Code Online (Sandbox Code Playgroud)
更新:忘了提到我正在使用MVC,我想在View中循环数据.States对象是ViewModel要查看的强类型属性之一.
更新:按要求更新以显示如何从控制器调用View -
[HttpPost]
public ActionResult Index(FormCollection form)
{
..some validations and some logic
ViewModel myViewModel = new ViewModel();
myViewModel.Countries = GetCountries(); -- this is where data get initialized
myViewModel.Data …Run Code Online (Sandbox Code Playgroud) 我有一个函数创建一个本地List<object>,其中对象是一个匿名类型.我需要返回这些结果Dictionary<string, SortedList<DateTime, double>>.
数据列表如下所示.
{ Security = "6752 JT", Date = {1/17/2011 12:00:00 AM}, zScore = 1 }
{ Security = "6753 JT", Date = {1/17/2011 12:00:00 AM}, zScore = 2 }
{ Security = "6754 JT", Date = {1/17/2011 12:00:00 AM}, zScore = 3 }
{ Security = "6752 JT", Date = {1/18/2011 12:00:00 AM}, zScore = 1 }
{ Security = "6753 JT", Date = {1/18/2011 12:00:00 AM}, zScore = 2 }
{ Security …Run Code Online (Sandbox Code Playgroud) 我创建了一个具有布尔属性和集合的对象.
我所做的:
我有一个在post上调用的方法,后者又调用另一个返回对象的方法.我的问题是我没有得到对象属性.
public object methodThatReturnsAnObject(string a, string b)
{
object data = new {isSaved = false, personsToCredit = ""}
// perform my code and if all is valid i set values to my object properties and return the object
data = new {isSaved = valid, personsToCredit = persons }
return data;
}
Run Code Online (Sandbox Code Playgroud)
我的另一种方法:
object Information = methodThatReturnsAnObject(string a, string b);
Run Code Online (Sandbox Code Playgroud)
我的问题是什么?当我调试Information对象包含我想要获取的两个属性但是当我键入Information.isSaved它时它说信息不包含定义isSaved?
c# ×10
linq ×2
.net ×1
.net-4.0 ×1
asp.net ×1
asp.net-mvc ×1
collections ×1
datagridview ×1
dictionary ×1
dynamic ×1
exception ×1
generics ×1
winforms ×1