상수 목록의 인라인 인스턴스화
나는 다음과 같이 시도합니다.
public const List<String> METRICS = new List<String>()
{
SourceFile.LOC,
SourceFile.MCCABE,
SourceFile.NOM,
SourceFile.NOA,
SourceFile.FANOUT,
SourceFile.FANIN,
SourceFile.NOPAR,
SourceFile.NDC,
SourceFile.CALLS
};
그러나 불행히도 이것은 작동하지 않습니다.
FileStorer.METRICS' is of type 'System.Collections.Generic.List<string>'. A const field of a reference type other than string can only be initialized with null.
이 문제를 어떻게 해결할 수 있습니까?
const
컴파일 타임 상 수용입니다. 당신은 할 수 단지 그것을 할 static readonly
,하지만 그건 단지에 적용됩니다 METRICS
(에 의해 일반적으로 대신 메트릭해야한다 변수 자체 .NET 명명 규칙 ). 목록을 변경할 수 없게 만들지 않습니다.METRICS.Add("shouldn't be here");
a를 사용 ReadOnlyCollection<T>
하여 포장 할 수 있습니다. 예를 들면 :
public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
(new List<String> {
SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn,
SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });
ReadOnlyCollection<T>
잠재적으로 변경 가능한 컬렉션을 래핑하지만 다른 어떤 것도 List<T>
이후에 액세스 할 수 없으므로 전체 컬렉션을 변경 불가능한 것으로 간주 할 수 있습니다.
(여기서 대문자는 대부분 추측입니다. 전체 이름을 사용하면 IMO가 더 명확 해집니다.)
당신이로 선언하든 IList<string>
, IEnumerable<string>
, ReadOnlyCollection<string>
당신은 다음, 그것은 단지 순서로 처리해야 기대하는 경우 또는 뭔가 다른 ... 당신에게 달려 IEnumerable<string>
아마도 가장 적절할 것이다. 순서가 중요하고 사람들이 색인으로 액세스 할 수 있도록하려면 IList<T>
적절할 수 있습니다. 불변성을 분명하게 만들고 싶다면 ReadOnlyCollection<T>
편리 할 수 있지만 융통성이 없다고 선언하십시오 .
static
readonly
대신 목록 을 사용해야합니다 . 목록을 변경할 수 없도록하려면 . ReadOnlyCollection<T>
대신 사용을 고려할 수 있습니다 List<T>
.
private static readonly ReadOnlyCollection<string> _metrics =
new ReadOnlyCollection<string>(new[]
{
SourceFile.LOC,
SourceFile.MCCABE,
SourceFile.NOM,
SourceFile.NOA,
SourceFile.FANOUT,
SourceFile.FANIN,
SourceFile.NOPAR,
SourceFile.NDC,
SourceFile.CALLS
});
public static ReadOnlyCollection<string> Metrics
{
get { return _metrics; }
}
.NET은 진정으로 변경할 수없는 컬렉션, 변경 가능한 컬렉션의 읽기 전용 뷰, 변경 가능한 컬렉션에 의해 구현 된 읽기 전용 인터페이스를 지원합니다 .
One such immutable collection is ImmutableArray<> which you can create as a.ToImmutableArray() in your example. Make sure to take a look at the other options MSDN lists because you may be better served by a different immutable collection. If you want to make copies of the original sequence with slight modifications, ImmutableList<> might be faster, for instance (the array is cheaper to create and access, though). Note that a.Add(...); is valid, but returns a new collection rather than changing a. If you have resharper, that will warn you if you ignore the return value of a pure method like Add (and there may be a roslyn extension to do something similar I'm unaware of). If you're going this route - consider skipping List<> entirely and going straight to immutable collections.
Read-only views of mutable collections are a little less safe but supported on older versions of .NET. The wrapping type is called ReadOnlyCollection<>, which in your example you might construct as a.AsReadOnly(). This collection does not guarantee immutability; it only guarrantees you can't change it. Some other bit of code that shares a reference to the underlying List<> can still change it. Also, ReadOnlyCollection also imposes some additional overhead; so you may not be winning much by avoiding immutable collections for performance reasons (TODO: benchmark this claim). You can use a read-only wrapper such as this even in a public API safely - there's no (non-reflection) way of getting the underlying list. However, since it's often no faster than immutable collections, and it's also not entirely safe, I recommend to avoid ReadOnlyCollection<> - I never use this anymore, personally.
Read-only interfaces implemented by mutable collections are even further down the scale of safety, but fast. You can simply cast List<> as IReadOnlyList<>, which you might do in your example as IReadOnlyList lst = a. This is my preferences for internal code - you still get static type safety, you're simply not protected from malicious code or code that uses type-checks and casts unwisely (but those are avoidable via code-reviews in my experience). I've never been bitten by this choice, but it is less safe than the above two options. On the upside, it incurs no allocations and is faster. If you commonly do this, you may want to define an extension method to do the upcast for you (casts can be unsafe in C# because they not only do safe upcasts, but possibly failing downcasts, and user-defined conversions - so it's a good idea to avoid explicit casts wherever you can).
Note that in all cases, only the sequence itself is read-only. Underlying objects aren't affected (e.g. an int or string are immutable, but more complicated objects may or may not be).
You are looking for a simple code, like this:
List<string> tagList = new List<string>(new[]
{
"A"
,"B"
,"C"
,"D"
,"E"
});
참고URL : https://stackoverflow.com/questions/4668365/inline-instantiation-of-a-constant-list
'code' 카테고리의 다른 글
Python으로 UTF8 CSV 파일 읽기 (0) | 2020.09.09 |
---|---|
jQuery : 선택한 파일 이름 가져 오기 (0) | 2020.09.09 |
.NET 콘솔에서 JSON WebService를 호출하는 가장 좋은 방법 (0) | 2020.09.09 |
"gdb가 코드 서명되었는지 확인하십시오-taskgated (8) 참조"-홈브류 코드 서명으로 gdb를 설치하는 방법은 무엇입니까? (0) | 2020.09.09 |
CountDownLatch 대 세마포 (0) | 2020.09.09 |