Ошибка cs0200 невозможно присвоить значение свойству или индексатору

Resources.Strings.Name= "";

Ошибка CS0200 Невозможно присвоить значение свойству или индексатору
«Strings.Name» — доступ только для чтения.

    /// <summary>
    ///   Ищет локализованную строку, похожую на Name.
    /// </summary>
    internal static string Name{
        get {
            return ResourceManager.GetString("Name", resourceCulture);
        }
    }

задан 9 июн 2017 в 17:51

code211218's user avatar

code211218code211218

3,9452 золотых знака27 серебряных знаков51 бронзовый знак

6

Документация: https://msdn.microsoft.com/ru-ru/library/7k989cfy(v=vs.90).aspx#Anchor_2

При построении приложения Visual Studio вызывает средство resgen.exe для преобразования ресурсов приложения во внутренний класс с именем Resources. Этот класс находится в файле Resources.Designer.cs, который вложен в файл Resources.resx в Обозревателе решений. Класс Resources инкапсулирует все ресурсы проекта в статические свойства get только для чтения, что дает возможность получения строго-типизированных ресурсов во время выполнения.

Для пользовательских настроек и временных данных можно использовать массу других вариантов, от банального Application.Settings, до полноценных баз данных.

ответ дан 10 июн 2017 в 14:41

rdorn's user avatar

popadev

0 / 0 / 0

Регистрация: 11.01.2016

Сообщений: 21

1

.NET 4.x

Невозможно присвоить значение свойству или индексатору — доступ только для чтения

17.01.2016, 17:01. Показов 40909. Ответов 2

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Доброго времени суток, ребят пишет ошибку:
Невозможно присвоить значение свойству или индексатору «string.this[int]» — доступ только для чтения
Сам код

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 public static void Otbor(string[] function)
        {
            double temp, cel, drob;
            string[] celS = new string[function.Length];
            string[] drobS = new string[function.Length];
            string str, drb = null;
            for (int i = 0; i < function.Length; i++)
            {
                temp = Convert.ToDouble(function[i]); //конвертируем в доубле
                cel = Math.Truncate(temp); // выделяем целую часть
                drob = temp - Math.Truncate(temp); //выделаем дробную часть
                celS[i] = Convert.ToString(cel); //конвертируем в строку целую часть
                drobS[i] = Convert.ToString(drob); //конвертируем в строку дробную часть
                str = drobS[i];
                for (int k = 0; k < drobS.Length; k++)
                {
                    drb[k] = str[k + 2];
                }
 
            }
        }

Указывает на

C#
1
2
3
{
      drb[k] = str[k + 2];
}



0



Woldemar89

TheGreatCornholio

1249 / 727 / 285

Регистрация: 30.07.2015

Сообщений: 2,403

17.01.2016, 17:25

2

popadev, таким образом string реализует IEnumerable<char>,
а IEnumerable не предполагает изменение обьектов.

Чтобы получить доступ, нужно строку преобразовать к char[] произвести операции и обратно string получить.
Попробуй так.

C#
1
2
3
char [] charStr = drb.ToCharArray();
charStr[k] = str[k + 2];
drb = new string(charStr);

Или лучше используй StringBuilder с самого начала, это для примера.

C#
1
2
3
StringBuilder someString = new StringBuilder(drb);
someString[k] = str[k + 2];
drb = someString.ToString();



5



0 / 0 / 0

Регистрация: 11.01.2016

Сообщений: 21

17.01.2016, 19:01

 [ТС]

3

Woldemar89, спасибо огромное!



0



Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0200

Compiler Error CS0200

04/22/2020

CS0200

CS0200

1990704a-edfa-4dbd-8477-d9c7aae58c96

Compiler error CS0200

Property or indexer ‘property’ cannot be assigned to — it is read only

An attempt was made to assign a value to a property, but the property does not have a set accessor or the assignment was outside of the constructor. Resolve the error by adding a set accessor. For more information, see How to declare and use read-write properties.

Examples

The following sample generates CS0200:

// CS0200.cs
public class Example
{
    private int _mi;
    int I
    {
        get
        {
            return _mi;
        }
        // uncomment the set accessor and declaration for _mi
        /*
        set
        {
            _mi = value;
        }
        */
    }

    public static void Main()
    {  
        Example example = new Example();
        example.I = 9;   // CS0200
    }
}  

The following sample uses auto-implemented properties and object initializers and still generates CS0200:

// CS0200.cs
public class Example
{
    int I
    {
        get;
        // uncomment the set accessor and declaration
        //set;
    }

    public static void Main()
    {  
        var example = new Example
        {
            I = 9   // CS0200
        };
    }
}

To assign to a property or indexer ‘property’ that’s read-only, add a set accessor or assign the value in the object’s constructor.

public class Example
{
    int I { get; }

    public Example()
    {
        I = -7;
    }
}

Strings are immutable, you cannot change them like this.
Use StringBuilder to make another string with changed characters, for example:

if (Start[i] == Middle[j])
{
    StringBuilder sb = new (Middle);
    (sb[i], sb[j]) = (sb[j], sb[i]);
    Middle = sb.ToString();
}

or even better — declare Middle as StringBuilder from the beginning, this will reduce string -> StringBuilder -> string conversions.
Char array is also an option if you only swap characters and never remove / add any.

C# Compiler Error

CS0200 – Property or indexer ‘property’ cannot be assigned to — it is read only

Reason for the Error

You will receive this error in your C# code when you attempt to assign a value to a property that does not have a set accessor and the assignment of the value was made outside the constructor.

For example, try to compile the below code snippet.

namespace DeveloperPubNamespace
{
    class Employee
    {
        public int Id { get; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.Id = 1;
        }
    }

}

This program has a class “Employee” with the Property “Id” that doesnot have a set accessor. We are attempting to assigning the value 1 to the Id via the instance inside the Main method.

This results with the error code CS0200.

Error CS0200 Property or indexer ‘Employee.Id’ cannot be assigned to — it is read only ConsoleApp3 C:UsersSenthilsourcereposConsoleApp3ConsoleApp3Program.cs 12 Active

Solution

To fix the error code CS0200, you should either add the set accessor or else assign the value via the constructor.

namespace DeveloperPubNamespace
{
    class Employee
    {
        public int Id { get; }
        public Employee()
        {
            Id = 1;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

}

Понравилась статья? Поделить с друзьями:
  • Ошибка cs0106 модификатор public недопустим для этого элемента
  • Ошибка cs0106 модификатор private недопустим для этого элемента
  • Ошибка cs0103 имя initializecomponent не существует в текущем контексте
  • Ошибка cs0101 пространство имен уже содержит определение для
  • Ошибка cs0004 pubg на ps4