我有一个返回所有枚举值的方法(但这不是重要的).重要的是它需要T
并返回IEnumerable<T>
.
private static IEnumerable<T> GetAllEnumValues<T>(T ob)
{
return System.Enum.GetValues(ob.GetType()).Cast<T>();
}
Run Code Online (Sandbox Code Playgroud)
要么
private static IEnumerable<T> GetAllEnumValues<T>(T ob)
{
foreach (var info in ob.GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
{
yield return (T) info.GetRawConstantValue();
}
}
Run Code Online (Sandbox Code Playgroud)
要使用此方法,您需要使用类的实例调用它 - 在本例中,使用我们要探索的枚举中的任何值:
GetAllEnumValues( Questions.Good );
Run Code Online (Sandbox Code Playgroud)
我想更改方法的签名以获取System.Type
in并能够像这样调用它:
GetAllEnumValues( typeof(Questions ));
Run Code Online (Sandbox Code Playgroud)
我不知道签名会是什么样子:
private static IEnumerable<?> GetAllEnumValues<?>(System.Type type)
Run Code Online (Sandbox Code Playgroud)
以及如何申请铸造或Convert.ChangeType
实现这一目标.
我不想打电话 GetAllEnumValues<Questions>( typeof(Questions ));
这甚至可能吗?
在试用了Azure的Service架构几天后,我仍然对以下四个关键词感到不舒服:*实例*节点*节点类型*缩放比例集。
他们的意思是什么?有什么区别?
我们有以下代码:
import time
def rec1(len):
if( len < 2): return 1;
return 2*rec1(len-1);
def rec2(len):
if( len < 2): return 1;
return rec2(len-1) + rec2(len-1);
def callAndReport(len, method):
time1 = time.time()
answer = method(len)
time2 = time.time()
print("{0} with {1}:{2} in {3:.0f} ms".format(len,method.__name__,answer, (time2-time1)*1000))
if __name__ == '__main__':
callAndReport(20,rec1)
callAndReport(20,rec2)
print('')
callAndReport(23,rec1)
callAndReport(23,rec2)
Run Code Online (Sandbox Code Playgroud)
此代码生成以下输出:
20 with rec1:524288 in 0 ms
20 with rec2:524288 in 642 ms
23 with rec1:4194304 in 0 ms
23 with rec2:4194304 in 4613 ms
Run Code Online (Sandbox Code Playgroud)
有人可以解释执行时间的差异吗?我想的很少,但我想确定一下.
为了完整性,我遇到的原始问题是下面的方法(可以很容易地表达为for循环,但这不是重点): …
您认为下面的两个代码之间哪个是最好的,或者您有另一种更有效的选择
第一的
List<int> g = new List<int>();
g.AddRange(listof1);
g.AddRange(listof2);
return g.GroupBy(a=>a)
.Select(root=>root.FirstOrDefault())
.ToList();
Run Code Online (Sandbox Code Playgroud)
第二
var rootIds = listof1.
Union(listof2)
.Select(rootId => rootId).ToList();
return rootIds;
Run Code Online (Sandbox Code Playgroud)