C#: открытый метод {получает {} набор {}} вопрос

Необходимо возвратить это как IntPtr. Возврат Системы. Строковый тип от функции PInvoke требует большого ухода. CLR должен передать память от собственного представления в управляемое. Это - легкая и предсказуемая операция.

проблема, хотя идет, что сделать с собственной памятью, которая была возвращена из нечто (). CLR принимает следующие два объекта о функции PInvoke, которая непосредственно возвращает строковый тип

  1. , собственная память должна быть освобождена
  2. , собственная память была выделена с CoTaskMemAlloc

Поэтому, это упорядочит строку и затем назовет CoTaskMemFree на собственном блобе памяти. Если Вы на самом деле не выделили эту память с CoTaskMemAlloc, это в лучшем случае вызовет катастрофический отказ в Вашем приложении.

для получения корректной семантики здесь необходимо возвратить IntPtr непосредственно. Тогда используйте Маршала. PtrToString* для получения до управляемого Строкового значения. Вы, возможно, все еще должны освободить собственную память, но это будет зависящий от реализации нечто.

5
задан jason 24 September 2009 в 13:14
поделиться

7 ответов

Try this:

// This returns an instance of type "Foo",
// since I didn't know the type of "list".
// Obviously the return type would need to
// match the type of whatever "list" contains.
public Foo this[int index]
{
    get { return list[index]; }
    set { list[index] = value; }
}

This is C#'s indexer syntax and it has some limitations (it's not as flexible as VB.NET's parameterful properties) but it does work for your specific example.

21
ответ дан 18 December 2019 в 05:24
поделиться

As others have shown, you can turn it into an indexer - which can have multiple parameters, by the way.

What you can't do is name an indexer in C#... although you can in VB. So you can't have two indexers, one called Foo and the other called Bar... you'd need to write properties which returned values which were themselves indexable. It's a bit of a pain, to be honest :(

6
ответ дан 18 December 2019 в 05:24
поделиться

This is called indexer property

public int this [int index]  
{      
     get { return list[index]; }      
     set { list[index] = value; }  
}
5
ответ дан 18 December 2019 в 05:24
поделиться

I think what you might be looking for is:

public Something this[int index]
{
    get
    {
         return list[index];
    }
    set
    {
         list[index] = value;
    }
}
3
ответ дан 18 December 2019 в 05:24
поделиться

For the record, Whilst the other answers are valid, you might also want to consider using the following approach:

public IList<Something> items { get; set; }

This could then be used as follows:

Something item = myFoo.items[1];

The other answers would be used in the following, slightly different, way:

Something item = myFoo[1];

The one you want depends on what exactly you are trying to achieve, which is difficult to determine without seeing the rest of the code.

1
ответ дан 18 December 2019 в 05:24
поделиться

Besides the indexer that has been mentioned several times now, another possibility is to make a custom class with an indexer and return an instance of it as a property.

Example:

public class IntList
{
    public IntList(IEnumerable<int> source)
    {
        items = source.ToArray();
        Squares = new SquareList(this);
    }

    private int[] items;

    // The indexer everyone else mentioned
    public int this[int index]
    {
        get { return items[index]; }
        set { items[index] = value; }
    }

    // Other properties might be useful:
    public SquareList Squares { get; private set; }

    public class SquareList
    {
        public SquareList(IntList list)
        {
            this.list = list;
        }

        private IntList list;

        public int this[int index]
        {
            get { return list.items[index] * list.items[index]; }
        }
    }
}
1
ответ дан 18 December 2019 в 05:24
поделиться

You can use indexator for solving this problem

public object this[string name]
        {
            get
            {
                int idx = FindParam(name);
                if (idx != -1)
                    return _params[idx].Value;

                throw new IndexOutOfRangeException(String.Format("Parameter \"{0}\" not found in this collection", name));
            }
            set 
            { 
                int idx = FindParam(name);
                if (idx != -1)
                    _params[idx].Value = value;
                else
                    throw new IndexOutOfRangeException(String.Format("Parameter \"{0}\" not found in this collection", name));
            }
        }
0
ответ дан 18 December 2019 в 05:24
поделиться
Другие вопросы по тегам:

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