익명 유형 목록의 선언
익명 유형의 목록 객체를 선언하는 방법이 있습니까? 내말은
List<var> someVariable = new List<var>();
someVariable.Add(
new{Name="Krishna",
Phones = new[] {"555-555-5555", "666-666-6666"}}
);
런타임에 컬렉션을 만들어야하기 때문입니다.
약간의 해커 리가 필요하지만 할 수 있습니다.
static List<T> CreateListFromSingle<T>(T value) {
var list = new List<T>();
list.Add(value);
return list;
}
var list = CreateListFromSingle(
new{Name="Krishna",
Phones = new[] {"555-555-5555", "666-666-6666"}}
);
다이나믹은 어떻습니까?
List<dynamic> dynamicList = new List<dynamic>();
dynamicList.Add(new { Name = "Krishna", Phones = new[] { "555-555-5555", "666-666-6666" } });
이와 같은 목록을 만들 수는 있지만 심각한 해커 리를 사용해야하며 "예제 별"상황을 사용해야합니다. 예를 들면 :
// create the first list by using a specific "template" type.
var list = new [] { new { Name="", Phones=new[] { "" } } }.ToList();
// clear the list. The first element was just an example.
list.Clear();
// start adding "actual" values.
list.Add(new { Name = "Krishna", Phones = new[] { "555-555-5555", "666-666-6666" } });
일반적으로 유형 인수에 대해 익명 유형으로 매개 변수화 된 모든 제네릭 유형의 인스턴스를 생성하기 위해 다른 사람들이 언급 한 예제 트릭에 의한 (아마도 나쁜 냄새가 나는) 캐스트를 사용할 수 있습니다. 그러나 List<T>
약간 덜 총체적인 방법이 있습니다.
var array = new[] {
new {
Name="Krishna",
Phones = new[] {"555-555-5555", "666-666-6666"}
}
};
var list = array.ToList();
제안 된 구문에 대한 스케치는 C # 3 또는 4 용으로 구현하지 않은 기능과 유사하지만 고려했습니다. 이 기능을 "mumble types"라고 부르며 다음과 같이됩니다.
List<?> myList = new List<?>() {
new {
Name="Krishna",
Phones = new[] {"555-555-5555", "666-666-6666"}
}
};
물론 "myList는 hrmmf의 새로운 목록입니다"라고 읽었 기 때문에 "mumble 유형"이라고 부릅니다. :-)
아이디어는 컴파일러가 이니셜 라이저를 살펴보고 "var"가 "이니셜 라이저를보고 변수의 유형이 무엇인지 파악하는 것과 동일한 방식으로 유형이 무엇인지 파악하기 위해 최선을 다하는 것"입니다. ". "var"를 "mumble"또는 "?"로 사용할지 여부 (Java가 관련 기능에서 수행하는 것과 유사 함) 또는 다른 것이 열린 질문입니다.
In any event, I wouldn't hold my breath waiting for this feature if I were you. It hasn't made the cut for several language versions so far, but it will stay on the list of possibilities for a while longer I think. If, hypothetically speaking, we were to be designing future versions of the language. Which we might or might not be. Remember, Eric's musings about future versions of C# are for entertainment purposes only.
You can't make a collection of an anonymous type like this.
If you need to do this, you'll need to either use List<object>
, or make a custom class or struct for your type.
Edit:
I'll rephrase this:
Although, technically, it's possible to make a list of an anonymous type, I would strongly recommend never doing this. There is pretty much always a better approach, as doing this is just making code that is nearly unmaintainable. I highly recommend making a custom type to hold your values instead of using anonymous types.
A custom type will have all of the same capabilities (since anonymous types are defined, by the compiler, at compile time), but will be much more understandable by the developer who follows you...
And just to play, too, here's my entry for "code I'd never actually want to use in the real world":
var customer = new { Name = "Krishna", Phones = new[] { "555-555-5555", "666-666-6666" } };
var someVariable = new[]{1}.Select(i => customer).ToList();
Here's an approach that is somewhat cleaner than many of the other suggestions:
var list = Enumerable.Repeat(new { Name = "", Phones = new[] { "" } }, 0)
.ToList();
// ...
list.Add(new { Name = "Krishna",
Phones = new[] { "555-555-5555", "666-666-6666" } });
I spent quite a lot of time trying to find a way to save myself some time using a list of anonymous types, then realised it was probably quicker just to use a private class inside the current class...
private class Lookup {
public int Index;
public string DocType;
public string Text;
}
private void MyMethod() {
List<Lookup> all_lookups = new List<Lookup> {
new Lookup() {Index=4, DocType="SuperView", Text="SuperView XML File"},
new Lookup() {Index=2, DocType="Word", Text="Microsoft Word Document"}
};
// Use my all_lookups variable here...
}
I don't think this is possible. Maybe in C# 4 using the dynamic keyword?
참고URL : https://stackoverflow.com/questions/2327594/declaration-of-anonymous-types-list
'program story' 카테고리의 다른 글
RecyclerView 가로 스크롤 스냅 중앙 (0) | 2020.10.20 |
---|---|
JSON 객체를 예쁘게 인쇄 된 JSON으로 변환하는 Angular 2 파이프 (0) | 2020.10.20 |
uitextview의 문자 수 제한 (0) | 2020.10.20 |
matplotlib에서 막대 높이의 합이 1 인 히스토그램 플로팅 (0) | 2020.10.20 |
문자열의 최소 및 최대 길이를 확인하지만 공백 일 수 있음 (0) | 2020.10.20 |