C#: ключевое слово и проверяющий на Нет

Я думаю, что вы только что неправильно сделали отступ:

theBoard = {'top left': ' ', 'top middle': ' ', 'top right': ' ',
            'center left': ' ', 'center middle': ' ', 'center right': ' ',
            'bottom left': ' ', 'bottom middle': ' ', 'bottom right': ' '}
def printBoard(board):
    print(board['top left'] + '|' + board['top middle'] + '|' + board['top right'])
    print('-+-+-')
    print(board['center left'] + '|' + board['center middle'] + '|' + board['center left'])
    print('-+-+-')
    print(board['bottom left'] + '|' + board['bottom middle'] + '|' + board['bottom right'])

turn = 'X'
for i in range (9):
    printBoard(theBoard)
    print('Turn for ' + turn + '.Move on which space?')
    move = input()
    theBoard[move] = turn
    if turn == 'X':
        turn = 'O'
    else:
        turn = 'X'
printBoard(theBoard)
262
задан Venkat 8 May 2019 в 20:59
поделиться

8 ответов

if(!(child is IContainer))

is the only operator to go (there's no IsNot operator).

You can build an extension method that does it:

public static bool IsA<T>(this object obj) {
    return obj is T;
}

and then use it to:

if (!child.IsA<IContainer>())

And you could follow on your theme:

public static bool IsNotAFreaking<T>(this object obj) {
    return !(obj is T);
}

if (child.IsNotAFreaking<IContainer>()) { // ...

Update (considering the OP's code snippet):

Since you're actually casting the value afterward, you could just use as instead:

public void Update(DocumentPart part) {
    part.Update();
    IContainer containerPart = part as IContainer;
    if(containerPart == null) return;
    foreach(DocumentPart child in containerPart.Children) { // omit the cast.
       //...etc...
283
ответ дан 23 November 2019 в 02:34
поделиться

Вы можете сделать это следующим образом:

object a = new StreamWriter("c:\\temp\\test.txt");

if (a is TextReader == false)
{
   Console.WriteLine("failed");
}
107
ответ дан 23 November 2019 в 02:34
поделиться

Гадкий? Я не согласен. Единственный другой путь (лично я считаю, что это «уродливее»):

var obj = child as IContainer;
if(obj == null)
{
   //child "aint" IContainer
}
5
ответ дан 23 November 2019 в 02:34
поделиться

The way you have it is fine but you could create a set of extension methods to make "a more elegant way to check for the 'NOT' instance."

public static bool Is<T>(this object myObject)
{
    return (myObject is T);
}

public static bool IsNot<T>(this object myObject)
{
    return !(myObject is T);
}

Then you could write:

if (child.IsNot<IContainer>())
{
    // child is not an IContainer
}
8
ответ дан 23 November 2019 в 02:34
поделиться

The is operator evaluates to a boolean result, so you can do anything you would otherwise be able to do on a bool. To negate it use the ! operator. Why would you want to have a different operator just for this?

3
ответ дан 23 November 2019 в 02:34
поделиться

Почему бы просто не использовать else?

if (child is IContainer)
{
  //
}
else
{
  // Do what you want here
}

Это хорошо, это знакомо и просто?

12
ответ дан 23 November 2019 в 02:34
поделиться

While the IS operator is normally the best way, there is an alternative that you can use in some cirumstances. You can use the as operator and test for null.

MyClass mc = foo as MyClass;
if ( mc == null ) { }
else {}
2
ответ дан 23 November 2019 в 02:34
поделиться

Метод расширения IsNot - хороший способ расширить синтаксис. Имейте в виду, что

var container = child as IContainer;
if(container != null)
{
  // do something w/ contianer
}

работает лучше, чем что-то вроде

if(child is IContainer)
{
  var container = child as IContainer;
  // do something w/ container
}

. В вашем случае это не имеет значения, когда вы возвращаетесь из метода. Другими словами, будьте осторожны, чтобы не выполнять как проверку типа, так и преобразование типа сразу после.

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

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