using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Bowin.Common.Cache
{
///
/// Provides formatting string representing types, methods and fields. The
/// formatting strings may contain arguments like {0}
/// filled at runtime with generic parameters or method arguments.
///
internal static class Formatter
{
///
/// Gets a formatting string representing a .
///
/// A .
/// A formatting string representing the type
/// where each generic type argument is represented as a
/// formatting argument (e.g. Dictionary<{0},P1}>.
///
public static string GettypeFormatString(Type type)
{
StringBuilder stringBuilder = new StringBuilder();
// Build the format string for the declaring type.
stringBuilder.Append(type.FullName);
if (type.IsGenericTypeDefinition)
{
stringBuilder.Append("<");
for (int i = 0; i < type.GetGenericArguments().Length; i++)
{
if (i > 0)
stringBuilder.Append(", ");
stringBuilder.AppendFormat("{{{0}}}", i);
}
stringBuilder.Append(">");
}
return stringBuilder.ToString();
}
///
/// Gets the formatting strings representing a method.
///
/// A .
///
public static MethodFormatStrings GetMethodFormatStrings(MethodBase method)
{
string typeFormat;
bool typeIsGeneric;
string methodFormat;
bool methodIsGeneric;
string parameterFormat;
StringBuilder stringBuilder = new StringBuilder();
typeFormat = GettypeFormatString(method.DeclaringType);
typeIsGeneric = method.DeclaringType.IsGenericTypeDefinition;
// Build the format string for the method name.
stringBuilder.Length = 0;
stringBuilder.Append("::");
stringBuilder.Append(method.Name);
if (method.IsGenericMethodDefinition)
{
methodIsGeneric = true;
stringBuilder.Append("<");
for (int i = 0; i < method.GetGenericArguments().Length; i++)
{
if (i > 0)
stringBuilder.Append(", ");
stringBuilder.AppendFormat("{{{0}}}", i);
}
stringBuilder.Append(">");
}
else
{
methodIsGeneric = false;
}
methodFormat = stringBuilder.ToString();
// Build the format string for parameters.
stringBuilder.Length = 0;
ParameterInfo[] parameters = method.GetParameters();
stringBuilder.Append("(");
for (int i = 0; i < parameters.Length; i++)
{
if (i > 0)
{
stringBuilder.Append(", ");
}
stringBuilder.Append("{{{");
stringBuilder.Append(i);
stringBuilder.Append("}}}");
}
stringBuilder.Append(")");
parameterFormat = stringBuilder.ToString();
return new MethodFormatStrings(typeFormat, typeIsGeneric, methodFormat, methodIsGeneric, parameterFormat);
}
///
/// Pads a string with a space, if not empty and not yet padded.
///
/// A string.
/// A padded string.
public static string NormalizePrefix(string prefix)
{
if (string.IsNullOrEmpty(prefix))
{
return "";
}
else if (prefix.EndsWith(" "))
{
return prefix;
}
else
{
return prefix + " ";
}
}
public static string FormatString(string format, params object[] args)
{
if (args == null)
return format;
else
return string.Format(format, args);
}
}
}