Sprache: C#
Hiermit kann man in .NET 2.0 in einer kleinen Funktion direkt mehrere Strings zusammen setzen.
/// <summary>
/// Combines a unlimited amount of parts to a path string.
/// </summary>
/// <param name="paths">The parts of the path to combine.</param>
/// <returns>Returns the combined path as string.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static string MultiCombine(params string[] paths)
{
if (paths == null)
{
throw new ArgumentNullException("paths", "paths cannot be null");
}
if (paths.Length < 2)
{
throw new ArgumentOutOfRangeException("paths", "paths cannot be less than 2");
}
string currentString = paths[0];
for (int i = 1; i < paths.Length; i++)
{
currentString = System.IO.Path.Combine(currentString, paths[i]);
}
return currentString;
}
/// <summary>
/// Combines a unlimited amount of parts to a path string.
/// </summary>
/// <param name="paths">The parts of the path to combine.</param>
/// <returns>Returns the combined path as string.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static string MultiCombine(params string[] paths)
{
if (paths == null)
{
throw new ArgumentNullException("paths", "paths cannot be null");
}
if (paths.Length < 2)
{
throw new ArgumentOutOfRangeException("paths", "paths cannot be less than 2");
}
string currentString = paths[0];
for (int i = 1; i < paths.Length; i++)
{
currentString = System.IO.Path.Combine(currentString, paths[i]);
}
return currentString;
}
Alte URL:
/snippet/multi-combine-ergaenzung-zu-path-combine/1387
Warum wurde diese Funktion nicht mit einer FOREACH Schleife gemacht? wäre doch eleganter oder?
Lässt sich streiten, ob [b]das[/b] eleganter aussieht…
[code]public static string MultiCombine(params string[] paths)
{
if (paths == null)
{
throw new ArgumentNullException(„paths“, „paths cannot be null“);
}
if (paths.Length < 2) { throw new ArgumentOutOfRangeException("paths", "paths cannot be less than 2"); } [b]string currentString = ""; foreach (string s in paths) { if (currentString == "") string currentString = s; else[/b] currentString = System.IO.Path.Combine(currentString, paths[i]); } return currentString; } [/code]
Ich nutzer immer string.Empty statt „“ für einen leeren string.
string currentString = string.Empty;
foreach (string path in paths)
{
if (currentString == string.Empty)
currentString = path;
else
currentString = System.IO.Path.Combine(currentString, path);
}
Wieso nimmt man da string.Empty ???
Hab sonst immer „“ genommen und bin nie auf irgendein Problem gestoßen…
Wenn mans in ne if Anweisung schreibt weiß man dass der Entwickler wirklich string.Empty meint und nicht aus versehen vergessen hat da nen string reinzuschreiben. Gilt bei uns sogar als Convention