Почему я должен использовать касательно ключевого слова и в объявлении и в Вызове?

Я использую отражение изрядное количество в моих модульных тестах, особенно когда вещами, которые я проверяю, являются анонимные типы. Я также использовал его в качестве способа легко клонироваться/копировать объекты модели. Вместо того, чтобы писать код, чтобы сделать это для каждого объекта модели, я могу легко создать объект конкретного типа с помощью отражения, опросить общественные собственности входящего объекта и вызвать методы set на клонированные объекты соответствующие свойства. Я также использую его со сгенерированными классами разработчика, которые реализуют те же сигнатуры методов, но не имеют связанного интерфейса. В тех случаях я могу опросить объект видеть, имеет ли он требуемый метод, и вызовите его, если он делает. Объекты LINQ2SQL похожи на это так в моей поддельной обертке контекста данных метод OnSubmit, я использую отражение, чтобы получить метод OnValidate и вызвать его для поблочного тестирования.

6
задан Community 23 May 2017 в 12:25
поделиться

6 ответов

This is because ref indicates that the parameter should be passed in by reference. It is something like pointer in C++

For example;

void CalFoo()
{
  var i=10;
  foo(ref i);  //i=11
}
void foo(ref int i)
{
   i++;
}

but

void CalFoo()
{
  var i=10;
  foo(i);  //i=10
}
void foo(int i)
{
   i++;
}

I think you can have both foo(ref int) and foo(int) in one single class. So if you don't specify the ref.. how does the compiler knows which one to call?

12
ответ дан 8 December 2019 в 02:53
поделиться

It enhances readability/understandability: When you look at the method call, you know that the ref value might change.

9
ответ дан 8 December 2019 в 02:53
поделиться

As the Method and the Caller may be "far" away from each other (Different Assemblies, you may not even have the source of the one containing the method), having to specify out and ref explicitly helps making the intent clear. So it's something for the user so that they really know what they do, not a technical necessity.

3
ответ дан 8 December 2019 в 02:53
поделиться

While ref could most of the time be inferred from the method signature, it's always obligatory due to the fact that it can change the behavior of the code after the method call completely. Consider:

string hello = "world";
MyMethod(ref hello);
Console.WriteLine(hello);

If the ref keyword hadn't been there you would always expect the code to print out "world", while in reality, it can print anything.

3
ответ дан 8 December 2019 в 02:53
поделиться

I have also heard (or read somewhere - myaybe it was in an interview with the language designers) that the reason (like for many other "features" in C#) is to remind the programmer that the function he is giong to call use the argument by reference.

1
ответ дан 8 December 2019 в 02:53
поделиться

(As mentioned, this is a dupe of this question.)

For one thing, it's used as part of method overloading:

public void Foo(string x) { ... }
public void Foo(ref string x) { ... }

...

string x = "";
Foo(x); // Which should be used if you didn't have to specify ref?

Now one answer could be to prohibit that sort of overloading... but I think it's a good thing for C# to require this at the caller's side as documentation:

  • The behaviour changes significantly when you use ref (or out)
  • By calling out the rare uses of ref/out, it means you never need to check whether the argument is being passed by value or reference
  • It also affects what you can pass (e.g. you can't pass a literal, or the result of a method call). This is clearer when it's explicit.

Note that C# 4 does allow implicit use of ref for COM methods as there are so many ref parameters which don't really have ref behaviour (or at least, they don't take advantage of it). In such cases the compiler introduces a new local variable so that from the caller's point of view the argument really is being passed by value:

ComMethod(x);

translates into:

MyType tmp = x;
ComMethod (ref tmp);

This is a good compromise for COM methods, but I'm glad it's not the case for normal managed code.

4
ответ дан 8 December 2019 в 02:53
поделиться
Другие вопросы по тегам:

Похожие вопросы: