Enumerable을 사용하는 것이 좋습니다.새 목록과 달리 ()IEnumerable을 초기화하는 ()?
Person 클래스가 있다고 가정하십시오.
public class Person
{
public string Name { get; set;}
public IEnumerable<Role> Roles {get; set;}
}
생성자에서 역할을 분명히 인스턴스화해야합니다. 이제는 다음과 같이 List로 사용했습니다.
public Person()
{
Roles = new List<Role>();
}
그러나 System.Linq
네임 스페이스 에서이 정적 메소드를 발견했습니다.
IEnumerable<T> Enumerable.Empty<T>();
에서 MSDN :
이
Empty(TResult)()
메소드는 빈 유형의 시퀀스를 캐시합니다TResult
. 반환하는 개체가 열거되면 요소가 생성되지 않습니다.경우에 따라이 메서드는 빈 시퀀스를 사용자 정의 메서드에 전달하는 데 유용합니다
IEnumerable(T)
. 또한와 같은 방법에 대한 중립 요소를 생성하는 데 사용할 수 있습니다Union
. 이 사용 예는 예제 섹션을 참조하십시오.
따라서 생성자를 작성하는 것이 낫습니까? 당신은 그것을 사용합니까? 왜? 또는 그렇지 않다면 왜 안됩니까?
public Person()
{
Roles = Enumerable.Empty<Role>();
}
대부분의 게시물이 요점을 놓쳤다 고 생각합니다. 빈 배열이나 빈 목록을 사용하더라도 객체는 객체이며 메모리에 저장됩니다. 가비지 콜렉터가 처리해야합니다. 처리량이 많은 응용 프로그램을 다루는 경우 눈에 띄는 영향을 줄 수 있습니다.
Enumerable.Empty
호출 당 객체를 생성하지 않으므로 GC에 대한로드가 줄어 듭니다.
코드가 처리량이 적은 위치에 있으면 미적 고려 사항으로 요약됩니다.
생각 Enumerable.Empty<T>
좀 더 명시 적으로하기 때문에 더 나은 : 코드가 명확하게 의도를 나타냅니다. 또한 조금 더 효율적일 수도 있지만 이는 단지 두 번째 이점입니다.
성능 측면에서 Enumerable.Empty<T>
구현 방법을 살펴 보겠습니다 .
그것은 반환 EmptyEnumerable<T>.Instance
로 정의된다 :
internal class EmptyEnumerable<T>
{
public static readonly T[] Instance = new T[0];
}
제네릭 형식의 정적 필드는 제네릭 형식 매개 변수별로 할당됩니다. 이것은 런타임이 사용자 코드 요구 유형에 대해서만 빈 배열을 느리게 생성하고 가비지 수집기에 압력을 가하지 않고 필요한만큼 인스턴스를 재사용 할 수 있음을 의미합니다.
재치 :
Debug.Assert(ReferenceEquals(Enumerable.Empty<int>(), Enumerable.Empty<int>()));
실제로 Roles
어떻게 든 속성 을 채우고 싶다고 가정하면 setter를 비공개로 만들고 생성자의 새 목록으로 초기화하여 캡슐화하십시오.
public class Person
{
public string Name { get; set; }
public IList<Role> Roles { get; private set; }
public Person()
{
Roles = new List<Role>();
}
}
정말로 공용 세터를 원한다면 Roles
값을 남겨두고 null
객체 할당을 피하십시오.
접근 방식의 문제점은 컬렉션에 항목을 추가 할 수 없다는 것입니다. 목록과 같은 개인 구조를 가지고 항목을 열거 형으로 표시합니다.
public class Person
{
private IList<Role> _roles;
public Person()
{
this._roles = new List<Role>();
}
public string Name { get; set; }
public void AddRole(Role role)
{
//implementation
}
public IEnumerable<Role> Roles
{
get { return this._roles.AsEnumerable(); }
}
}
If you intend some other class to create the list of roles (which I wouldn't recommend) then I wouldn't initialise the enumerable at all in Person.
The typical problem with exposing the private List as an IEnumerable is that the client of your class can mess with it by casting. This code would work:
var p = new Person();
List<Role> roles = p.Roles as List<Role>;
roles.Add(Role.Admin);
You can avoid this by implementing an iterator:
public IEnumerable<Role> Roles {
get {
foreach (var role in mRoles)
yield return role;
}
}
The larger problem here would be exposing Roles
as a public field.
the following looks better:
public class Person
{
public string Name { get; set; }
private List<Role> _roles = null;
public IEnumerable<Role> Roles
{
get {
if (_roles != null)
return _roles;
else
return Enumerable.Empty<Role>();
}
}
}
And maybe you should take a look at returning it as a ReadonlyCollection, depending on how you want to use it.
And Enumerable.Empty isn't better
here, just a little more efficient when Roles usually stays empty.
'Programing' 카테고리의 다른 글
Android Studio 프로젝트를 빌드 할 때 Stacktrace 또는 디버그 옵션을 추가하는 방법 (0) | 2020.07.02 |
---|---|
Swift 앱에서 로컬 데이터를 저장하는 방법은 무엇입니까? (0) | 2020.07.02 |
C #에서 매개 변수를 사용하여 저장 프로 시저를 호출하십시오. (0) | 2020.07.02 |
matplotlib에서 플롯을 업데이트하는 방법은 무엇입니까? (0) | 2020.07.01 |
Java & = 연산자가 & 또는 &&를 적용합니까? (0) | 2020.07.01 |