Что является преимуществами неявной типизации в C# 3.0> +

Я видел пару ответов, ссылающихся на команду cut, но все они были удалены. Немного странно, что никто не уточнил это, потому что я думаю, что это одна из наиболее полезных команд для такого рода вещей, особенно для анализа файлов журнала с разделителями.

В случае разбиения этого конкретного примера на массив сценариев bash tr, вероятно, более эффективен, но может использоваться cut и более эффективен, если вы хотите вытянуть определенные поля из середины.

Пример:

$ echo "bla@some.com;john@home.com" | cut -d ";" -f 1
bla@some.com
$ echo "bla@some.com;john@home.com" | cut -d ";" -f 2
john@home.com

Очевидно, что вы можете поместить это в цикл и выполнить итерацию параметра -f для независимого извлечения каждого поля.

Это становится более полезным, когда у вас есть файл журнала с разделителями, например:

2015-04-27|12345|some action|an attribute|meta data

cut очень удобно, чтобы иметь возможность cat этот файл и выбрать определенное поле для дальнейшего использования. обработки.

6
задан Jeff Atwood 31 July 2009 в 16:51
поделиться

7 ответов

It's mostly syntactic sugar. It's really your preference. Unless when using anonymous types, then using var is required. I prefer implicit typing wherever possible though, it really shines with LINQ.

I find it redundant to type out a type twice.

List<string> Foo = new List<string>();

When I can easily just type var when it's obvious what the type is.

var Foo = new List<string>();
8
ответ дан 8 December 2019 в 05:56
поделиться

I started what turned out to be a hugely controversial thread when I first signed on here (my choice of "evilness" to describe general use of var was obviously a terrible choice.) Needless to say, I have more appreciation for var than I did before I started that thread, as well as a better understanding of how it can be usefully used:

The evilness of 'var' in C#?

Some good reasons to use var:

  • Brevity
  • Reduction of Repetition (DRY)
  • Reduced refactoring effort
  • Supports anonymous types (key reason it was added to C#)
4
ответ дан 8 December 2019 в 05:56
поделиться

var is useful for anonymous types, which do not have names for you to use.

var point = new {X = 10, Y = 10};

This will create an anonymous type with properties X and Y. It's primarily used to support LINQ though. Suppose you have:

class Person
{
    public String Name {get; set;}
    public Int32 Age {get; set;}
    public String Address {get; set;}
    // Many other fields
}

List<Person> people; // Some list of people

Now suppose I want to select only the names and years until age 18 of those people who are under the age of 18:

var minors = from person in people where person.Age < 18 select new {Name = person.Name, YearsLeft = 18 - person.Age};

Now minors contains a List of some anonymous type. We can iterate those people with:

foreach (var minor in minors)
{
    Console.WriteLine("{0} is {1} years away from age 18!", minor.Name, minor.YearsLeft);
}

None of this would otherwise be possible; we would need to select the whole Person object and then calculate YearsLeft in our loop, which isn't what we want.

5
ответ дан 8 December 2019 в 05:56
поделиться

Have a look at this questions. Maybe they'll help you decide.

Use of var keyword in C#
https://stackoverflow.com/questions/633474/c-do-you-use-var

2
ответ дан 8 December 2019 в 05:56
поделиться

It allows me to not repeat myself unnecessary. Consider this:

Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();

We have a very long typename repeated twice on the same line twice with absolutely no benefit. Furthermore, if you ever need to refactor this, you'll need to update the type twice. Whereas this is just as expressive:

var dict = new Dictionary<string, List<int>>();

There's still no doubt about type of dict here, but the code is shorter, and I would claim that it is easier to read as well.

2
ответ дан 8 December 2019 в 05:56
поделиться

The overarching reason for the implicit typing was to support anonymous types, like those produced by LINQ queries. They can also be a big benefit when dealing with complex-typed generics...something like Dictionary>. That's not too complex, but imagine enumerating...

foreach KeyValuePair<int,List<string>> pair in myDictionary
{

}

is simplified with implicit typing.

0
ответ дан 8 December 2019 в 05:56
поделиться

While the var keyword was primarily introduced to support anonymous types, the main argument I've seen for using it more widely is for brevity/more readable code, plus fitting more on your line of code:

Dictionary<string, double> data = new Dictionary<string, double>();
versus
var data = new Dictionary<string, double>();

Though not a good reason for most people, I also like the var keyword as a blind programmer, as I listen to the code being read out and thus here the variable name after just one syllabul :-)

0
ответ дан 8 December 2019 в 05:56
поделиться
Другие вопросы по тегам:

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