C #에서 상수 사전 만들기
s를 s 로 상수 (런타임으로 변경하지 않음) 매핑 을 만드는 가장 효율적인 방법은 무엇입니까 ?string
int
const Dictionary 사용하려고 시도했지만 작동하지 않았습니다.
적절한 의미 로 불변 래퍼 를 구현할 수는 있지만 여전히 정확하게 보이지는 않습니다.
요청한 사람들을 위해 생성 된 클래스에서 IDataErrorInfo 를 구현 중이며 columnName 조회를 설명자 배열로 만드는 방법을 찾고 있습니다.
나는 스위치가 문자열을 받아들이는 것을 알지 못했습니다 (테스트 할 때 오타! d' oh!). 그래서 내가 사용할 것입니다. 감사!
C #에서 컴파일 타임으로 생성 된 상수 사전을 만드는 것은 실제로 간단한 작업이 아닙니다. 실제로, 여기의 답변 중 어느 것도 실제로 그것을 달성하지 못합니다.
꼭 좋은 것은 아니지만 요구 사항을 충족하는 솔루션이 하나 있습니다. C # 사양에 따라 스위치 케이스 테이블은 상수 해시 점프 테이블로 컴파일됩니다. 즉, 일련의 if-else 문이 아닌 상수 사전입니다. 따라서 다음과 같은 switch-case 문을 고려하십시오.
switch (myString)
{
case "cat": return 0;
case "dog": return 1;
case "elephant": return 3;
}
이것이 바로 당신이 원하는 것입니다. 그리고 그래, 나도 알아
현재 프레임 워크에는 귀중한 소수의 컬렉션이 있습니다. .NET 3.5에서 비교적 고통스럽지 않은 옵션을 생각할 수 있습니다.
사용 Enumerable.ToLookup()
- Lookup<,>
클래스는 불변입니다 (그러나 rhs에 대한 다중 값). 당신은 이것을 Dictionary<,>
아주 쉽게 할 수 있습니다 :
Dictionary<string, int> ids = new Dictionary<string, int> {
{"abc",1}, {"def",2}, {"ghi",3}
};
ILookup<string, int> lookup = ids.ToLookup(x => x.Key, x => x.Value);
int i = lookup["def"].Single();
enum Constants
{
Abc = 1,
Def = 2,
Ghi = 3
}
...
int i = (int)Enum.Parse(typeof(Constants), "Def");
이것은 "CONST Dictionary"에 접근 할 수있는 가장 가까운 것입니다.
public static int GetValueByName(string name)
{
switch (name)
{
case "bob": return 1;
case "billy": return 2;
default: return -1;
}
}
컴파일러는 코드를 최대한 깨끗하게 빌드 할 수있을 정도로 똑똑합니다.
4.5+ 프레임 워크를 사용하는 경우 ReadOnlyDictionary (목록의 경우 ReadOnly Collection)를 사용하여 읽기 전용 매핑 / 상수를 수행합니다. 다음과 같은 방식으로 구현됩니다.
static class SomeClass
{
static readonly ReadOnlyDictionary<string,int> SOME_MAPPING
= new ReadOnlyDictionary<string,int>(
new Dictionary<string,int>()
{
{ "One", 1 },
{ "Two", 2 }
}
)
}
네임 스페이스 나 클래스를 사용하여 값을 중첩하지 않습니까? 불완전 할 수 있지만 매우 깨끗합니다.
public static class ParentClass
{
// here is the "dictionary" class
public static class FooDictionary
{
public const string Key1 = "somevalue";
public const string Foobar = "fubar";
}
}
이제 .ParentClass.FooDictionary.Key1 등에 액세스 할 수 있습니다.
사전에 대한 변경 불가능한 표준 인터페이스가없는 것 같으므로 래퍼를 만드는 것이 유감스럽게도 유일한 합리적인 옵션처럼 보입니다.
편집 : Marc Gravell은 내가 놓친 ILookup을 찾았습니다. 그래도 여전히 새 래퍼를 만들지 않아도되지만 To.Lookup ()으로 Dictionary를 변환해야합니다.
If this is a need constrained to a specific scenario, you might be better off with a more business-logic-oriented interface:
interface IActiveUserCountProvider
{
int GetMaxForServer(string serverName);
}
I am not sure why no one mentioned this but in C# for things that I cannot assign const, I use static read-only properties.
Example:
public static readonly Dictionary<string, string[]> NewDictionary = new Dictionary<string, string[]>()
{
{ "Reference1", Array1 },
{ "Reference2", Array2 },
{ "Reference3", Array3 },
{ "Reference4", Array4 },
{ "Reference5", Array5 }
};
Why not:
public class MyClass
{
private Dictionary<string, int> _myCollection = new Dictionary<string, int>() { { "A", 1 }, { "B", 2 }, { "C", 3 } };
public IEnumerable<KeyValuePair<string,int>> MyCollection
{
get { return _myCollection.AsEnumerable<KeyValuePair<string, int>>(); }
}
}
참고URL : https://stackoverflow.com/questions/268084/creating-a-constant-dictionary-in-c-sharp
'IT박스' 카테고리의 다른 글
dom 렌더링이 완료된 후 지시문을 실행하려면 어떻게해야합니까? (0) | 2020.07.23 |
---|---|
Angular.js 속성 지시문에 여러 속성을 어떻게 전달합니까? (0) | 2020.07.23 |
쉘 스크립트에 도움말 메소드를 추가하려면 어떻게해야합니까? (0) | 2020.07.23 |
C 데이터 유형은“대부분의 컴퓨터에서 직접 지원”되는 방식은 무엇입니까? (0) | 2020.07.23 |
단위 테스트, NUnit 또는 Visual Studio? (0) | 2020.07.23 |