在 C# 中是否有一个很好的现有或即将推出的替代方法来声明方法中的数据结构?可以使用匿名类型,但声明它们有困难。假设我有一个假设的课程:
class ThingsManager
{
private void DoThings(IEnumerable<Thing> things)
{
var thingLocations = new Dictionary<string, string>();
foreach(var thing in things)
{
// some complicated logic and checks for current thing;
// if current thing satisfies all conditions:
var thingName = thing.Name;
var thingLocation = location; // taken somewhere from upper lines
thingLocations.Add(thingName, thingLocation);
}
// ... later
foreach(var thingLocation in thingLocations)
{
// here I don't know what is the key and what does the value mean.
// I could use Linq and anonymous types, but sometimes it is clearer
// to use foreach if the logic is complicated
}
}
}
现在,我想看到什么:
class ThingsManager
{
private void DoThings(IEnumerable<Thing> things)
{
struct ThingLocations
{
string ThingName {get;set;}
string Location {get;set;}
}
var thingLocations = new List<ThingLocations>();
foreach(var thing in things)
{
// some complicated logic and checks for current thing;
// if current thing satisfies all conditions:
var thingName = thing.Name;
var thingLocation = location; // taken somewhere from upper lines
thingLocations.Add(new ThingLocation(thingName, thingLocation));
}
// ... later
foreach(var thingLocation in thingLocations)
{
// now here I can use thingLocation.ThingName
// or thingLocation.Location
}
}
}
我也可以在类中声明结构,但在我的函数之外的任何地方使用它都没有意义。如果我的函数是唯一可以使用此数据结构的地方会更好。我正在寻找一种更好的方法来处理这种情况,或者至少能够声明匿名类型。