メソッドでデータ構造を宣言するための、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
}
}
}
クラスで構造体を宣言することもできますが、関数以外の場所で構造体を使用することは意味がありません。私の関数がこのデータ構造を使用できる唯一の場所であるとよいでしょう。私はそのような状況を処理するためのより良い方法を探しています、または少なくとも匿名型を宣言することができます。