IT박스

C #이 참조 반환을 지원하지 않는 이유는 무엇입니까?

itboxs 2020. 6. 21. 20:28
반응형

C #이 참조 반환을 지원하지 않는 이유는 무엇입니까?


.NET은 참조 반환을 지원하지만 C #은 지원하지 않는다는 것을 읽었습니다. 특별한 이유가 있습니까? 왜 내가 다음과 같은 것을 할 수 없습니까?

static ref int Max(ref int x, ref int y) 
{ 
  if (x > y) 
    return ref x; 
  else 
    return ref y; 
} 

이 질문은 2011 년 6 월 23 일제 블로그 의 주제였습니다 . 좋은 질문 감사합니다!

C # 팀은 C # 7에서이를 고려하고 있습니다. 자세한 내용은 https://github.com/dotnet/roslyn/issues/5233 을 참조하십시오.

업데이트 :이 기능은 C # 7에 도입되었습니다!


당신이 올바른지; .NET은 변수에 대한 관리되는 참조를 반환 하는 메서드를 지원 합니다. .NET은 다른 변수에 대한 관리 참조가 포함 된 로컬 변수 도 지원 합니다. 그러나 .NET은 가비지 수집 스토리를 지나치게 복잡하게하므로 다른 변수에 대한 관리 참조가 포함 된 필드 또는 배열지원하지 않습니다 . 또한 "변수에 대한 관리 참조"유형은 object로 변환 할 수 없으므로 다음과 같이 사용할 수 없습니다. 제네릭 형식 또는 메서드에 대한 형식 인수)

어떤 이유로 논평자 "RPM1984"는이 사실에 대한 인용을 요구했다. RPM1984 .NET의이 기능에 대한 정보는 CLI 스펙 파티션 I 섹션 8.2.1.1, "관리 포인터 및 관련 유형"을 읽으십시오.

이 두 기능을 모두 지원하는 C # 버전을 만드는 것은 전적으로 가능합니다. 그런 다음과 같은 일을 할 수 있습니다

static ref int Max(ref int x, ref int y) 
{ 
  if (x > y) 
    return ref x; 
  else 
    return ref y; 
} 

그리고 그것을 호출

int a = 123;
int b = 456; 
ref int c = ref Max(ref a, ref b); 
c += 100;
Console.WriteLine(b); // 556!

나는 이러한 기능을 지원하는 C 번호의 버전을 구축하는 것이 가능하다는 것을 경험적으로 알고 내가 그렇게 때문에를 . 고급 프로그래머, 특히 관리되지 않는 C ++ 코드를 이식하는 사람들은 실제로 포인터를 사용하고 메모리를 고정시키는 데 큰 어려움을 겪지 않고도 참조로 작업을 수행하는 더 많은 C ++과 같은 기능을 요구합니다. 관리되는 참조를 사용하면 가비지 수집 성능을 저하시키지 않으면 서 이러한 이점을 얻을 수 있습니다.

우리는이 기능을 고려하여 실제로 다른 내부 팀에 피드백을받을 수있을 정도로 충분히 구현했습니다. 그러나 현재 우리의 연구에 따르면이 기능은 실제로 지원되는 언어 기능으로 만들기에 충분한 호소력이나 사용 사례가 충분하지 않다고 생각합니다 . 우선 순위가 높고 시간과 노력이 제한되어 있으므로이 기능을 곧 사용할 수 없습니다.

또한 제대로 수행하려면 CLR을 약간 변경해야합니다. 현재 CLR은 이러한 상황을 감지하는 검출기가 없기 때문에 환급 방법을 합법적 이지만 검증 할 수없는 것으로 취급합니다.

ref int M1(ref int x)
{
    return ref x;
}

ref int M2()
{
    int y = 123;
    return ref M1(ref y); // Trouble!
}

int M3()
{
    ref int z = ref M2();
    return z;
}

M3 returns the contents of M2's local variable, but the lifetime of that variable has ended! It is possible to write a detector that determines uses of ref-returns that clearly do not violate stack safety. What we would do is write such a detector, and if the detector could not prove stack safety, then we would not allow the usage of ref returns in that part of the program. It is not a huge amount of dev work to do so, but it is a lot of burden on the testing teams to make sure that we've really got all the cases. It's just another thing that increases the cost of the feature to the point where right now the benefits do not outweigh the costs.

If you can describe for me why it is you want this feature, I would really appreciate that. The more information we have from real customers about why they want it, the more likely it will make it into the product someday. It's a cute little feature and I'd like to be able to get it to customers somehow if there is sufficient interest.

(See also related questions Is it Possible to Return a Reference to a Variable in C#? and Can I use a reference inside a C# function like C++?)


You are talking about methods that return a reference to a value type. The only built-in example in C# that I know of is the array-accessor of a value type:

public struct Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

and now create an array of that struct:

var points = new Point[10];
points[0].X = 1;
points[0].Y = 2;

In this case points[0], the array indexer, is returning a reference to struct. It is impossible to write your own indexer (for example for a custom collection), that has this same "return a reference" behavior.

I didn't design the C# language so I don't know all the reasoning behind not supporting it, but I think that the short answer might be: we can get along just fine without it.


You could always do something like:

public delegate void MyByRefConsumer<T>(ref T val);

public void DoSomethingWithValueType(MyByRefConsumer<int> c)
{
        int x = 2;
        c(ref x);
        //Handle potentially changed x...
}

C# 7.0 has support for returning references. See my answer here.

참고URL : https://stackoverflow.com/questions/6339602/why-doesnt-c-sharp-support-the-return-of-references

반응형