Вопрос

i wonder why ! cannot be applied

this is my code :

  for (int i = 0; i < rowcol.GetLength(0); i++)
            {
                for (int j = 0; j < rowcol[i].GetLength(0); j++)
                {

                     var top = !((rowcol[i-1][j])) ? rowcol[i-1][j] : '';
                    var bottom = !(rowcol[i+1][j]) ? rowcol[i+1][j] : '';
                    var left = !(rowcol[i][j-1]) ? rowcol[i][j-1] : '';
                    var right = !(rowcol[i][j+1]) ? rowcol[i][j+1] : '';


                }
            }

i have a jagged array that , i am reading the values from a textfile . i am having error with operator ! cannot be applied to string , but i and j is int , , yes rowcol is reading a string from a textfile .

please tell me if u need the full code . Help is appreciated thanks

Это было полезно?

Решение

The issue is that rowcol[i-1][j] is a string, and ! cannot be applied to a string. The same applies for each of your four lines.

Edit: If your goal is to check that the string is not null or empty, try instead:

var top = !(String.isNullOrEmpty(rowcol[i - 1][j])) ? rowcol[i - 1][j] : '';

and so on, or, if you know that the string will be null and not empty,

var top = (rowcol[i - 1][j]) != null) ? rowcol[i - 1][j] : '';

Другие советы

Try:

for (int i = 0; i < rowcol.GetLength(0); i++)
{
    for (int j = 0; j < rowcol[i].GetLength(0); j++)
    {

         var top = !(rowcol[i-1][j]=="") ? rowcol[i-1][j] : '';
        var bottom = !(rowcol[i+1][j]=="") ? rowcol[i+1][j] : '';
        var left = !(rowcol[i][j-1]=="") ? rowcol[i][j-1] : '';
        var right = !(rowcol[i][j+1]=="") ? rowcol[i][j+1] : '';
    }
}

Or,

for (int i = 0; i < rowcol.GetLength(0); i++)
{
    for (int j = 0; j < rowcol[i].GetLength(0); j++)
    {
        var top = rowcol[i-1][j]!="" ? rowcol[i-1][j] : '';
        var bottom = rowcol[i+1][j]!="" ? rowcol[i+1][j] : '';
        var left = rowcol[i][j-1]!="" ? rowcol[i][j-1] : '';
        var right = rowcol[i][j+1]!="" ? rowcol[i][j+1] : '';
    }
}

The ! syntax is called the logical negation operator and it is a unary operator, which means it can only be applied to a single operand of type bool. In other words you can only use the ! operator against a single Boolean quantity, like this:

if(!String.IsNullOrEmpty(someStringValue))
{
    // Do something here
}

You are trying to apply the ! operator to a string value and that is the reason you are getting an error.

You need to have the ! operator applied to a Boolean quantity, like this:

var top = !(rowcol[i-1][j] == String.Empty) ? rowcol[i-1][j] : '';

OR

var top = !(String.isNullOrEmpty(rowcol[i - 1][j])) ? rowcol[i - 1][j] : '';
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top