dfa*_*dfa 18 language-agnostic oop
一段时间后,每个程序员都会得到一组实用程序类.其中一些是真正的编程珍珠,它们在你的几个项目中被重用.例如,在java中:
class Separator {
private String separator;
private boolean called;
public Separator(String aSeparator) {
separator = aSeparator;
called = false;
}
@Override
public String toString() {
if (!called) {
called = true;
return "";
} else {
return separator;
}
}
}
Run Code Online (Sandbox Code Playgroud)
和:
public class JoinHelper {
public static <T> String join(T... elements) {
return joinArray(" ", elements);
}
public static <T> String join(String separator, T... elements) {
return joinArray(separator, elements);
}
private static <T> String joinArray(String sep, T[] elements) {
StringBuilder stringBuilder = new StringBuilder();
Separator separator = new Separator(sep);
for (T element : elements) {
stringBuilder.append(separator).append(element);
}
return stringBuilder.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
什么是你最重用的类?
具有日志记录和电子邮件功能的实用程序类。包含扩展方法的扩展类。一个报告类,基本上利用报告服务 Web 服务,并可以轻松地将报告传输为 excel、pdf 等。
示例...
1.) 实用程序类(静态)
public static void LogError(Exception ex)
{
EventLog log = new EventLog();
if (ex != null)
{
log.Source = ConfigurationManager.AppSettings["EventLog"].ToString();
StringBuilder sErrorMessage = new StringBuilder();
if (HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null)
{
sErrorMessage.Append(HttpContext.Current.Request.Url.ToString() + System.Environment.NewLine);
}
sErrorMessage.Append(ex.ToString());
log.WriteEntry(sErrorMessage.ToString(), EventLogEntryType.Error);
}
}
Run Code Online (Sandbox Code Playgroud)
2.) 扩展类
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
Run Code Online (Sandbox Code Playgroud)