我正在尝试编写一个通用的Parse方法,该方法转换并返回NamedValueCollection中的强类型值.我尝试了两种方法,但这两种方法都通过装箱和拆箱来获得价值.有谁知道避免拳击的方法?如果你在生产中看到这个你会不喜欢它,它的性能有多糟糕?
Usuage:
var id = Request.QueryString.Parse<int>("id");
Run Code Online (Sandbox Code Playgroud)
尝试#1:
public static T Parse<T>(this NameValueCollection col, string key)
{
string value = col[key];
if (string.IsNullOrEmpty(value))
return default(T);
if (typeof(T) == typeof(int))
{
//return int.Parse(value); // cannot convert int to T
//return (T)int.Parse(value); // cannot convert int to T
return (T)(object)int.Parse(value); // works but boxes
}
if (typeof(T) == typeof(long))
{
return (T)(object)long.Parse(value); // works but boxes
}
...
return default(T);
}
Run Code Online (Sandbox Code Playgroud)
尝试#2(使用反射):
public static T Parse<T>(this NameValueCollection col, string key)
{
string value …Run Code Online (Sandbox Code Playgroud) 特定
public Class Example
{
public static void Foo< T>(int ID){}
public static void Foo< T,U>(int ID){}
}
Run Code Online (Sandbox Code Playgroud)
问题:
如何在创建MethodInfo对象时指定任一方法?
Type exampleType = Type.GetType("fullyqualifiednameOfExample, namespaceOfExample");
MethodInfo mi = exampleType.GetMethod("Foo", BindingFlags.Public|BindingFlags.Static, null, new Type[] {typeof(Type), typeof(Type) }, null);
Run Code Online (Sandbox Code Playgroud)参数4使编译器非常不满
使用反射,我如何获得在.NET Core中实现某些特定接口的所有类型?我注意到.NET 4.6中可用的方法不再可用.
例如,此代码不起作用.
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
Run Code Online (Sandbox Code Playgroud)
它抛出The name 'AppDomain' does not exist in the current context错误.
我目前正在处理c#中的反射.后:
Assembly.LoadFile(@"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.7\System.Numerics.Vectors.dll").GetTypes()
Run Code Online (Sandbox Code Playgroud)
我发现了这个:( [System.Numerics.Matrix4x4], [System.Numerics.Matrix4x4+CanonicalBasis], [System.Numerics.Matrix4x4+VectorBasis]
有来自"System.Numerics.Vectors.dll"的反映类型)我知道Matrix4x4是结构,但我找不到关于CanonicalBasis和VectorBasis的任何信息,以及"+"在这种情况下的含义.我正在做进一步的研究,另一个奇怪的事情是:
Assembly.LoadFile(@"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.7\System.Numerics.Vectors.dll").GetType("System.Numerics.Matrix4x4+VectorBasis").FullName
"System.Numerics.Matrix4x4+VectorBasis"
Run Code Online (Sandbox Code Playgroud)
但:
Assembly.LoadFile(@"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.7\System.Numerics.Vectors.dll").GetType("System.Numerics.Matrix4x4+VectorBasis").Name
"VectorBasis"
Run Code Online (Sandbox Code Playgroud)
此外,当我查看Matrix4x4 + VectorBasis的成员时,有这样的成员:
[System.Numerics.Vector3* Element0]
Run Code Online (Sandbox Code Playgroud)
它是像c ++中的原始指针吗?或者它是什么?
PS我在c#interactive中这样做,但我认为它对结果没有任何影响.
我使用StrictMode来查找非SDK用法:
if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectNonSdkApiUsage()
.penaltyLog()
.build());
}
Run Code Online (Sandbox Code Playgroud)
现在,我违反了政策:
D/StrictMode: StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/view/textclassifier/logging/ SmartSelectionEventTracker$SelectionEvent;->selectionAction(IIILandroid/view/textclassifier/TextClassification;)Landroid/view/textclassifier/logging/ SmartSelectionEventTracker$SelectionEvent;
at android.os.StrictMode.lambda$static$1(StrictMode.java:428)
at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2)
at java.lang.Class.getDeclaredMethodInternal(Native Method)
at java.lang.Class.getPublicMethodRecursive(Class.java:2075)
at java.lang.Class.getMethod(Class.java:2063)
at java.lang.Class.getMethod(Class.java:1690)
at bzi.a(SourceFile:11)
at bzq.a(SourceFile:12)
at org.chromium.content.browser.selection.SmartSelectionClient.<init>(SourceFile:5)
at bzZ.a(Unknown Source:7)
at org.chromium.android_webview.AwContents.e(SourceFile:193)
at org.chromium.android_webview.AwContents.d(SourceFile:153)
at org.chromium.android_webview.AwContents.<init>(SourceFile:81)
at uY.run(SourceFile:15)
at ahv.a(SourceFile:13)
at ahw.run(SourceFile:2)
at org.chromium.base.ThreadUtils.b(SourceFile:31)
at ahv.a(SourceFile:7)
at com.android.webview.chromium.WebViewChromiumFactoryProvider.b(SourceFile:6)
at com.android.webview.chromium.WebViewChromium.init(SourceFile:111)
at android.webkit.WebView.<init>(WebView.java:678)
at android.webkit.WebView.<init>(WebView.java:604)
at android.webkit.WebView.<init>(WebView.java:587)
at android.webkit.WebView.<init>(WebView.java:574)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at …Run Code Online (Sandbox Code Playgroud) 在 C# 中,我在给定的类(非静态)中定义了以下方法:
int MyMethod(ScriptEngine script, int a, int b) {
return a + b;
}
void MyMethod2(ScriptEngine script, string c) {
// do something with c
}
Run Code Online (Sandbox Code Playgroud)
我想创建包装 lambda / Action / Delegate / MethodInfo(所有这些都被脚本引擎接受),它会自动传递ScriptEngine和this从给定的预定义变量。
到目前为止,我已经尝试过:
// With overloads up to 16 template parameters
Action<T1> Wrap<T1>(Action<ScriptEngine, T1> func, ScriptEngine script) {
return (Action<T1>) ((t1) => func(script, t1));
}
Run Code Online (Sandbox Code Playgroud)
但是当调用 MyMethod2 时,我得到了The type arguments for method … cannot be inferred from the usage. Try specifying …
我上过一堂课:
class A {
public final Integer orgId;
}
Run Code Online (Sandbox Code Playgroud)
我将其替换为Java 17中的记录:
record A (Integer orgId) {
}
Run Code Online (Sandbox Code Playgroud)
另外,我有一个通过反射进行验证的代码,该代码适用于常规类,但不适用于记录:
Field[] fields = obj.getClass().getFields(); //getting empty array here for the record
for (Field field : fields) {
}
Run Code Online (Sandbox Code Playgroud)
在 Java 17 中通过反射获取 Record 对象字段及其值的正确方法是什么?
我目前正面临运营商的新问题.使用以下代码,我想使输出与if ... else在C#中使用pair 时的输出相同.
var method = new DynamicMethod("dummy", null, Type.EmptyTypes);
var g = method.GetILGenerator();
g.Emit(OpCodes.Ldstr, "string");
g.Emit(OpCodes.Ldstr, "string");
g.Emit(OpCodes.Call, typeof(String).GetMethod("op_Equality", new Type[]{typeof(string), typeof(string)}));
g.Emit(OpCodes.Ldc_I4, 0);
g.Emit(OpCodes.Ceq);
g.Emit(OpCodes.Brtrue_S, );
var action = (Action)method.CreateDelegate(typeof(Action));
action();
Console.Read();
Run Code Online (Sandbox Code Playgroud)
我的问题是:
BR和BR_S,Brtrue和Brtrue_S,Brfalse和Brfalse_S和类似的说明?谢谢.
c# reflection reflection.emit system.reflection memory-address
几乎所有人都知道Java中的字符串是不可变的.最近我发现了一些可能暗示它并不总是正确的东西.我们试试这段代码吧:
System.out.println("-------- BEFORE MODIFICATIONS --------");
String beforeTest = new String("Original");
System.out.println(beforeTest);
java.lang.reflect.Field valueField = String.class.getDeclaredField("value");
valueField.setAccessible(true);
valueField.set("Original", "Modified".toCharArray());
System.out.println("-------- AFTER MODIFICATIONS --------");
System.out.println(beforeTest);
System.out.println("Original");
String test = new String("Original");
System.out.println(test);
String test2 = new String("Original 2");
System.out.println(test2);
Run Code Online (Sandbox Code Playgroud)
输出将是:
-------- BEFORE MODIFICATIONS --------
Original
-------- AFTER MODIFICATIONS --------
Original
Modified
Modified
Original 2
Run Code Online (Sandbox Code Playgroud)
这个技巧如何运作?JVM如何知道应该更改哪些对象以及哪些对象不应该更改?这个伎俩的机制是什么?为什么已经创建的beforeTest字符串没有改变?这个技巧真的会贬低这个strings are immutable原则吗?
如何在Scala 2.10的反射中反映包层次结构?我可以找出存在哪些子包,或者父包是什么?
reflection ×10
c# ×6
.net ×2
generics ×2
java ×2
lambda ×2
.net-core ×1
android ×1
java-17 ×1
java-record ×1
methodinfo ×1
scala ×1
scala-2.10 ×1
string ×1