当前位置: 首页 > 编程语言 > C#

c#如何获取CallerMember的类型名分享

时间:2023-04-11 11:42:31 C#

c#如何获取CallerMember的类型名我上过这门课publicboolfooMethod([CallerMemberName]stringmembername="")){//这根据类型和方法返回一个值}publicvoidGetMethods(){//这里使用反射填充MethodsList}}而这个属性类//这个属性从数据库中获取一些东西,然后fooMethod检查这个属性成员publicclassCustomAttribute{publicstringfullMethodPath;公共布尔一些东西;publicboolCustomAttribute([CallerMemberName]stringmembername=""){fullMethodPath=**DerivedType**+membername//我需要在这里获取membernameparent的类型。//这里我想获取CustClass,而不是fooBase}}然后我有这个publicclassCustClass:fooBase{[CustomAttribute()]publicstringmethod1(){if(fooMethod()){....}}}我需要CallerMember是否有类似[CallerMemberName]的东西来获取Caller的类所有者?这并非万无一失,但.NET的约定是每个文件都有一个类型,并将文件命名为与该类型相同的名称。我们的工具也倾向于执行此约定,即Resharper和VisualStudio。因此,从文件路径推断类型名应该是合理的。公共类MyClass{publicvoidMyMethod([CallerFilePath]stringcallerFilePath=null,[CallerMemberName]stringcallerMemberName=null){varcallerTypeName=Path.GetFileNameWithoutExtension(callerFilePath);Console.WriteLine(callerTypeName);Console.WriteLine(callerMemberName);在我看来,CompilerServices提供的信息太少,无法从调用方法中获取类型。您可以做的是使用StackTrace(请参阅StackTrace)查找调用方法(使用GetMethod()),然后使用Reflection获取类型。考虑以下事项:使用System.Runtime.CompilerServices;公共类Foo{publicvoidMain(){what();}publicvoidwhat(){Bar.GetCallersType();}publicstaticclassBar{[MethodImpl(MethodImplOptions.NoInlining)]//这将防止编译器内联。publicstaticvoidGetCallersType(){StackTracestackTrace=newStackTrace(1,false);//Captures1frame,false表示不收集文件信息vartype=stackTrace.GetFrame(1).GetMethod().DeclaringType;//这将为您提供typeof(Foo);注意——正如@Jay在评论中所说,它可能非常昂贵,但它确实有效。编辑:我发现了几篇比较性能的文章,与反射相比它确实非常昂贵,反射也被认为不是最好的。请参阅:[1][2]编辑2:因此,深入研究StackTrace,使用它确实不安全甚至昂贵。由于每个将被调用的方法都将用[CustomAttribute()]标记,所有包含它的方法都可以收集在一个静态列表中。公共类CustomAttribute:Attribute{publicstaticListMethodsList=newList();staticCustomAttribute(){varmethods=Assembly.GetExecutingAssembly()//如果此方法在库中,则使用.GetCallingAssembly(),或者两者都在.GetTypes().SelectMany(t=>t.GetMethods()).Where(m=>m.GetCustomAttributes(typeof(CustomAttribute),false).Length>0).ToArray();方法列表=新列表(方法);}公共字符串fullMethodPath;公共布尔一些东西;publicCustomAttribute([CallerMemberName]stringmembername=""){varmethod=MethodsList.FirstOrDefault(m=>m.Name==membername);如果(方法==null||method.DeclaringType==null)返回;//假设不会发生,但安全是第一位的fullMethodPath=method.DeclaringType.Name+membername;//以任何你想要的方式解决它//我需要在这里获取membernameparent的类型。//这里我想获取CustClass,而不是fooBase}}使用这种方法来满足您的精确需求。调用者成员当然,获取调用者成员名称在对象模型中并不是“自然”的。这就是C#工程师在编译器中引入CallerMemberName的原因。真正的敌人是重复,基于堆栈的解决方案效率低下。[CallerMemberName]允许在不重复且无不利影响的情况下获取信息。调用者类型但获取调用者成员类型自然易得,无需重复。怎么做在fooMethod中添加“caller”参数,不需要特殊属性。publicboolfooMethod(objectcaller,[CallerMemberName]stringmembername=""){类型callerType=caller.GetType();//这会根据类型和方法返回一个值returntrue;}并调用它:fooMethod(this);这回答了你说的问题//hereIwanttogetCustClass,notfooBaseandthat'swhatyou'llget.其他不会被炒的情况。虽然这完全符合您的要求,但在其他不同的情况下它不起作用。在这些情况下,[CallerMemberType]可能有意义。但是,这些情况的解决方案大多在调用者的源文件中本地化,因此恕我直言,它们并不是真正的大问题。以上就是C#学习教程:c#中如何获取CallerMember的类型名。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。涉及侵权,请点击维权联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢