Преобразование типа в C#

лагерь REST имеет некоторые руководящие принципы, что мы можем использовать для стандартизации способа, которым мы используем глаголы HTTP. Это полезно при создании УСПОКОИТЕЛЬНОГО API, как Вы делаете.

Вкратце: ДОБЕРИТЕСЬ должно быть Только для чтения т.е. не иметь никакого эффекта на состояние сервера. POST используется для создания ресурса на сервере. ПОМЕЩЕННЫЙ используется, чтобы обновить или создать ресурс. УДАЛИТЕ используется для удаления ресурса.

, Другими словами, если Ваше действие API изменяет состояние сервера, REST советует нам использовать POST/помещать/удалять, но не ДОБИРАТЬСЯ.

Агенты пользователя обычно понимают, что выполнение нескольких СООБЩЕНИЙ плохо и предостережет от него, потому что намерение POST состоит в том, чтобы изменить состояние сервера (например, заплатить за товары на контроле), и Вы, вероятно, не хотите делать это дважды!

Выдерживают сравнение с ПОЛУЧЕНИЕМ, которое можно сделать часто, как Вам нравится (идемпотент).

19
задан fhcimolin 8 August 2019 в 12:38
поделиться

4 ответа

Casting is usually a matter of telling the compiler that although it only knows that a value is of some general type, you know it's actually of a more specific type. For example:

object x = "hello";

...

// I know that x really refers to a string
string y = (string) x;

There are various conversion operators. The (typename) expression form can do three different things:

  • An unboxing conversion (e.g. from a boxed integer to int)
  • A user-defined conversion (e.g. casting XAttribute to string)
  • A reference conversion within a type hierarchy (e.g. casting object to string)

All of these may fail at execution time, in which case an exception will be thrown.

The as operator, on the other hand, never throws an exception - instead, the result of the conversion is null if it fails:

object x = new object();
string y = x as string; // Now y is null because x isn't a string

It can be used for unboxing to a nullable value type:

object x = 10; // Boxed int
float? y = x as float?; // Now y has a null value because x isn't a boxed float

There are also implicit conversions, e.g. from int to long:

int x = 10;
long y = x; // Implicit conversion

Does that cover everything you were interested in?

64
ответ дан 30 November 2019 в 02:02
поделиться

Casting from one data type to another.

For a general reading see this.

See also msdn

0
ответ дан 30 November 2019 в 02:02
поделиться

See this or this:

Because C# is statically-typed at compile time, after a variable is declared, it cannot be declared again or used to store values of another type unless that type is convertible to the variable's type

...

However, you might sometimes need to copy a value into a variable or method parameter of another type. For example, you might have an integer variable that you need to pass to a method whose parameter is typed as double. Or you might need to assign a class variable to a variable of an interface type. These kinds of operations are called type conversions. In C#, you can perform the following kinds of conversions

2
ответ дан 30 November 2019 в 02:02
поделиться

Casting means creating a reference to an object that is of a different type to the reference you're currently holding. You can do upcasting or downcasting and each has different benefits.

Upcasting:

string greeting = "Hi Bob";
object o = greeting;

This creates a more general reference (object) from the more specific reference (string). Maybe you've written code that can handle any object, like this:

Console.WriteLine("Type of o is " + o.GetType());

That code doesn't need to be changed no matter what objects you set o to.

Downcasting:

object o = "Hi Bob";
string greeting = (string)o;

Here you want a more specific reference. You might know that the object is a string (you can test this e.g.:

if (o is string)
{ do something }

Now you can treat the reference as a string instead of an object. E.g. a string has a length (but an object doesn't), so you can say:

Console.WriteLine("Length of string is " + greeting.length);

Which you can't do with an object.

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

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