我有一个接口,定义了一些带属性的方法.需要从调用方法访问这些属性,但我所拥有的方法不会从接口中提取属性.我错过了什么?
public class SomeClass: ISomeInterface
{
MyAttribute GetAttribute()
{
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true);
if (attributes.Count() == 0)
throw new Exception("could not find MyAttribute defined for " + methodBase.Name);
return attributes[0] as MyAttribute;
}
void DoSomething()
{
MyAttribute ma = GetAttribute();
string s = ma.SomeProperty;
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个dll包含许多都继承自CommandBase类的类.我正在尝试使用C#中的反射来获取所有这些类(CommandA,CommandB,CommandC等)的实例,以便我可以在每个类上调用特定方法.这是我到目前为止:
//get assemblies in directory.
string folder = Path.Combine(HttpContext.Current.Server.MapPath("~/"), "bin");
var files = Directory.GetFiles(folder, "*.dll");
//load each assembly.
foreach (string file in files)
{
var assembly = Assembly.LoadFile(file);
if (assembly.FullName == "MyCommandProject")
{
foreach (var type in assembly.GetTypes())
{
if (!type.IsClass || type.IsNotPublic) continue;
if(type is CommandBase)
{
var command = Activator.CreateInstance(type) as CommandBase;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有2个问题.第一个问题是"if(type is CommandBase")行给出以下警告:
给定的表达式永远不是提供的类型CommandBase.
第二个问题是我无法弄清楚如何获取实际对象的实例(CommandA,CommandB等...),仅将其转换为CommandBase是不够的.
我正在写一些验证码.代码将传递到Web服务中的数据并决定它是否可以执行操作,或者向调用者返回他们错过了某些字段等的消息.
我有它主要工作除了数组.我使用[RequiredField]属性标记属性以表示所需的字段.所以,如果这是我的一些数据,
public enum EnumTest
{
Value1,
Value2
}
[DataContract]
public class DummyWebserviceData
{
[DataMember]
[RequiredField]
public EnumTest[] EnumTest{ get; set; }
[DataMember]
[RequiredField]
public DummyWebserviceData2[] ArrayOfData { get; set; }
}
[DataContract]
public class DummyWebserviceData2
{
[DataMember]
[RequiredField]
public string FirstName { get; set;}
[DataMember]
[RequiredField]
public string LastName { get; set;}
[DataMember]
public string Description { get; set;}
}
Run Code Online (Sandbox Code Playgroud)
那我该怎么办?我有日期验证和字符串工作.它使用递归来获取数据所需的任何深度级别.
但是......那么那两个阵列怎么样呢.第一个是枚举数组.我想检查一下这个数组不是空的情况.
第二个是DummyWebserviceData2值的数组.我需要拉出每个值并单独查看它.
为了简化我编写的代码,它看起来像这样,
foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
if (propertyInfo.PropertyType.IsArray)
{
// this craps out
object[] array …Run Code Online (Sandbox Code Playgroud) Type t = typeof(bool);
string typeName = t.Name;
Run Code Online (Sandbox Code Playgroud)
在这个简单的例子中,typeName将具有该值"Boolean".我想知道是否/如何让它说出来"bool".
对于int/Int32,double/Double,string/String也是如此.
假设我想确定是否Admin继承自ActiveRecord::Base.一种方法是这样做Admin.new.kind_of? ActiveRecord::Base,但是实例化一个未使用的Admin对象.
有没有创建Admin对象的简单方法?
谢谢
typeof当我们想要获取指定类型的Type实例时,我们可以使用C#关键字.但是,如果我想MethodInfo通过它的参考得到一个方法,我可以使用什么?
例如,我有一个简单的控制台应用程序.它包含Program.Main方法.我希望MethodInfo通过使用类似的东西methodinfoof(Program.Main).我有这个问题,因为方法名称可能会改变,所以我不能只使用Type.GetMethodInfo(string MethodName)它.
我有大约10 000种方法可供我使用MethodInfo,因此在我的方法中添加任何自定义属性或其他任何方法都不是解决方案.
在过去,当Invocation(一个实验性实用程序)是标准库的一部分时,可以"动态"调用方法,如下所示:
"Hello!" o 'substring(0, 4) // to get Any back
"Hello!" oo 'substring(0, 4) // for an automatic unsafe cast to expected type
Run Code Online (Sandbox Code Playgroud)
如何使用新的Scala反射API执行此操作?
我只需要使用System.Type从AutoFixture创建一个对象.但是,似乎没有过载CreateAnonymous(),只需要一种类型.他们都期望编译时通用T.有没有办法将System.Type转换为T?
编辑使用细节:
我正在使用AutoMapper,它有一个用于注入组件的钩子,以支持复杂的映射场景:
void ConstructServicesUsing(System.Func<Type,object> constructor)
Run Code Online (Sandbox Code Playgroud)
从签名中可以看出,客户端可以注册FuncAutoMapper何时需要注入服务(主要是ValueResolver实现).
在生成版本中,此方法调用我的StructureMap容器来检索组件.但是,在单元测试我的映射代码时,我必须提供存根实现,否则AutoMapper会抛出异常.由于我使用AutoFixture + Moq作为我的自动锁定容器,因此让AF新建一个完全水合的存根似乎很自然,所以我可以集中精力编写单元测试代码.
我知道classPHP 5.5上有一个静态字段,但我必须坚持使用PHP 5.4.是否可以从变量中获取完全限定的类名?
例:
namespace My\Awesome\Namespace
class Foo {
}
Run Code Online (Sandbox Code Playgroud)
以及代码中的其他地方:
public function bar() {
$var = new \My\Awesome\Namespace\Foo();
// maybe there's something like this??
$fullClassName = get_qualified_classname($var);
// outputs 'My\Awesome\Namespace\Foo'
echo $fullClassName
}
Run Code Online (Sandbox Code Playgroud) 我使用Scala的Java Reflection时遇到了问题.我的代码:
case class MyClass(id: String, value: Double)
def create(values: Map[String, Any]): MyClass = {
val constructor = classOf[MyClass].getConstructors.head
val arguments = classOf[MyClass].getDeclaredFields().map( f => values(f.getName) )
constructor.newInstance(arguments: _*).asInstanceOf[MyClass]
}
create(Map("id" -> "CE0D23A", "value" -> 828.32))
Run Code Online (Sandbox Code Playgroud)
我的问题是,我需要传递Map [String,Any],因为其中一个值是Double,但newInstance需要Object,而不是Any.
我尝试使用scalas宇宙:
case class MyClass(id: String, value: Double)
def create(values: Map[String, Any]): MyClass = {
val m = universe.runtimeMirror(getClass.getClassLoader)
val myClass = universe.typeOf[MyClass].typeSymbol.asClass
val cm = m.reflectClass(myClass)
val ctro = universe.typeOf[MyClass].declaration(universe.nme.CONSTRUCTOR).asMethod
val ctorm = cm.reflectConstructor(ctro)
ctorm(values: _*).asInstanceOf[MyClass]
}
create(Map("id" -> "CE0D23A", "value" -> …Run Code Online (Sandbox Code Playgroud) reflection ×10
c# ×6
scala ×2
.net ×1
attributes ×1
autofixture ×1
automapper ×1
inheritance ×1
interface ×1
java ×1
methodinfo ×1
oop ×1
php ×1
ruby ×1
typeof ×1
types ×1