我有一个Java的枚举:
public enum Months
{
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
}
Run Code Online (Sandbox Code Playgroud)
我想通过索引访问枚举值,例如
Months(1) = JAN;
Months(2) = FEB;
...
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
我想在C#中理解AST.我想知道,Compile()这个例子的确切方法是什么.
// Some code skipped
Expression<Func<string, int, int, string>> data = Expression.Lambda<Func<string, int, int, string>>(
Expression.Call(s, typeof(string).GetMethod(“Substring”, new Type[] { typeof(int), typeof(int) }), a, b),
s, a, b
);
Func<string, int, int, string> fun = data.Compile();
Run Code Online (Sandbox Code Playgroud)
为了防止误解,我理解Expression.Lambda和Expression.Call构建.我感兴趣的是Compile()方法.它以某种方式生成真正的MSIL?我能看到MSIL吗?
我想知道,对象验证的最佳实践是什么.对案例一或案例二有任何额外的争论吗?还有另外一种方法吗?
我不搜索任何验证库,我只想做简单的验证.
案例一
class A {
public void doSomething(MyObject o) {
try {
validate(o);
doSomethingUseful(o);
} catch (ValidationException e) {
Logger.getLogger().warn(e);
}
}
private void validate(MyObject o) throws ValidationException
{
if (o.getXYZ() == null)
throw new ValidationException("Field XYZ cannot be null");
}
private void doSomethingUseful(MyObject o) { //some funny stuff }
}
Run Code Online (Sandbox Code Playgroud)
案例二
class A {
public void doSomething(MyObject o) {
if (validate(o)) {
doSomethingUseful(o);
} else
Logger.getLogger().warn("Object is invalid");
}
}
private boolean validate(MyObject o)
{
if (o.getXYZ() == …Run Code Online (Sandbox Code Playgroud) 我有一个适配器I1来ILogger实现如下:
class BAdapter() implements I1
{
void logA() { // nothing }
void logB() { new BLogger().log() }
void logC() { // nothing }
}
Run Code Online (Sandbox Code Playgroud)
我想编写JUnit测试,即验证的功能,但我发现它有点问题,因为我不能注入我的模仿对象,而不是BLogger,或验证返回值.我找到了几个可能的解决方案,但我不确定,哪个是最好的.
案例一:
添加void setLogger(Logger l)到BAdapter类.
class BAdapter() implements I1
{
private Logger logger = new BLogger();
public void logB() { logger.log() }
public void setLogger(Logger l) { logger = l }
.. //rest of methods
}
Run Code Online (Sandbox Code Playgroud)
缺点:为什么要添加从未在"真实",非测试代码中使用过的setter?
案例二:BAdapter在测试包中
添加受保护的工厂方法和sublcass .
class BAdapter() implements …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写F#解析器.根据规范,let表达式如下:
let value-defn in expr
Run Code Online (Sandbox Code Playgroud)
我正在使用Try F#进行测试.我尝试下面的代码,解析没有错误.
#light "off"
let a = 1
Run Code Online (Sandbox Code Playgroud)
然而,根据手册中,应始终包含在关键字.为什么它是有效的F#代码?