Skip to content

Instantly share code, notes, and snippets.

@d630
Created June 14, 2018 22:38
Show Gist options
  • Save d630/ba16f88455b71bceb6e96c82473e0280 to your computer and use it in GitHub Desktop.
Save d630/ba16f88455b71bceb6e96c82473e0280 to your computer and use it in GitHub Desktop.
Indexers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace csharp
{
public class Foo
{
private string[] s;
private int len;
public Foo(int l)
{
len = l;
s = new string[l];
}
public string this[int i]
{
get
{
return s[i];
}
set
{
s[i] = value;
}
}
public string this[string str, int m = 1]
{
get
{
StringBuilder sb = new StringBuilder();
if (m > 1)
{
for (int i = 0; i < len; i++)
{
if (s[i] == str)
sb.Append(i.ToString() + ",");
}
sb.Remove(sb.Length - 1, 1);
}
else
{
for (int i = 0; i < len; i++)
{
if (s[i] == str)
{
sb.Append(i.ToString());
break;
}
}
}
return sb.ToString();
}
set
{
if (m > 1)
{
for (int i = 0; i < len; i++)
{
if (s[i] == str)
s[i] = value;
}
}
else
{
for (int i = 0; i < len; i++)
{
if (s[i] == str)
{
s[i] = value;
return;
}
}
}
}
}
}
public class Program
{
static void Main(string[] args)
{
Foo f = new Foo(5);
f[0] = "null";
f[1] = "eins";
f[2] = "zwei";
f[3] = "drei";
f[4] = "drei";
for (int i = 0; i < 5; i++)
Console.WriteLine(f[i]);
f["drei", 2] = "DREI";
for (int i = 0; i < 5; i++)
Console.WriteLine(f[i]);
Console.WriteLine(f["DREI"]);
Console.WriteLine(f["DREI", 2]);
f["DREI"] = "drei";
Console.WriteLine(f[3] + "\n" + f[4]);
Console.ReadKey();
}
}
}
@d630
Copy link
Author

d630 commented Jun 14, 2018

Als Typ gehen mindestens int, enum und string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment