所以,如果我有:
public class ChildClass : BaseClass
{
public new virtual string TempProperty { get; set; }
}
public class BaseClass
{
public virtual string TempProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如何使用反射来查看ChildClass是否隐藏了TempProperty的Base实现?
我想在c#和vb.net之间做出不可知的答案
是否可以确定是否已覆盖虚拟方法:
class ABase {
public void DoSomething(object p)
{
p.Process();
if( /* DoSomethingExtra is implemented */ )
DoSomethingExtra(p);
}
public virtual void DoSomethingExtra(object p) { }
}
class ADerived {
public override void DoSomethingExtra(object p)
{
p.ProcessMore();
}
}
Run Code Online (Sandbox Code Playgroud)
我意识到这个例子看起来很愚蠢(例如,你为什么不调用DoSomethingExtra(),因为它没有做任何事情).我向你保证,我有一个合法的案例.有任何想法吗?
有没有办法判断一个方法是否是一个覆盖?例如
public class Foo
{
public virtual void DoSomething() {}
public virtual int GimmeIntPleez() { return 0; }
}
public class BabyFoo: Foo
{
public override int GimmeIntPleez() { return -1; }
}
Run Code Online (Sandbox Code Playgroud)
是否可以反思BabyFoo并判断是否GimmeIntPleez是覆盖?
我有一些代码(用于帮助url路由)试图在控制器中找到一个动作方法.
我的控制器看起来像这样:
public ActionResult Item(int id)
{
MyViewModel model = new MyViewModel(id);
return View(model);
}
[HttpPost]
public ActionResult Item(MyViewModel model)
{
//do other stuff here
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
以下代码尝试查找与url操作匹配的方法:
//cont is a System.Type object representing the controller
MethodInfo actionMethod = cont.GetMethod(action);
Run Code Online (Sandbox Code Playgroud)
今天这个代码抛出了一个System.Reflection.AmbiguousMatchException: Ambiguous match found有意义的,因为我的两个方法具有相同的名称.
我看了一下Type对象的可用方法,发现public MethodInfo[] GetMethods();它似乎做了我想要的,除了搜索具有特定名称的方法似乎没有重载.
我可以使用这个方法并搜索它返回的所有内容,但我想知道是否有另一种(更简单的)方法来获取具有特定名称的类中的所有方法的列表,当有多个时.
我正在编写 php 服务和我们的 crm 之间的互操作。我需要做的一件事是确保简单类型被转换为 ToString() 以便稍后在 json 转换器中使用。
我什至不确定“简单类型”的名称是什么,但它可以这样定义...“代表低级变量类型的对象,包含单个值,而不是类或任何具有可执行函数等的对象”
我发现 int、string、bool、double 和令人惊讶的 enum 将使用 ToString() 并获得相当可预测的结果。
int x = 0;
bool y = true;
double z = 1.59 // money
CustomEnum theEnum = CustomEnum.somevalue;
Run Code Online (Sandbox Code Playgroud)
x.ToString() 结果为“0”
y.ToString() 结果为“true”
z.ToString() 结果为“1.59”
theEnum.ToString() 结果为“somevalue”
但如果我用这个:
List<int> iList = new List<int>();
iList.Add(1);
MyClass theClass = new MyClass();
Run Code Online (Sandbox Code Playgroud)
iList.ToString() 结果为“System.Collections.Generic.List`1[System.Int32]” Class.ToString() 结果为“STTI.NKI.Interop.MyClass”
我不限于列表。我可以有一个 ExpandoObject 或一个类等。
我完全理解为什么会发生这种情况,并且我想知道是否有一种快速方法来确定未知类型的对象是否将 ToString() 转换为预期值,而不是类型名称。我发现做类似的事情是一种反模式
switch (theObject.GetType())
case typeof(int):
case typeof(bool):
case typeof(doulble):
etc
Run Code Online (Sandbox Code Playgroud)
我不确定这些术语是什么,所以谷歌搜索我的答案很困难。
c# ×5
reflection ×3
.net ×1
inheritance ×1
object ×1
oop ×1
overriding ×1
tostring ×1
typename ×1
vb.net ×1