我使用反射来查看System.String的内部字段,我找到了三个字段:
m_arrayLength
m_stringLength
m_firstChar
Run Code Online (Sandbox Code Playgroud)
我不明白这是如何工作的.
m_arrayLength是某个数组的长度.这个阵列在哪里?它显然不是字符串类的成员字段.
m_stringLength很有意义.这是字符串的长度.
m_firstChar是字符串中的第一个字符.
所以我的问题是字符串的其余字符在哪里?如果不在字符串类中,则存储字符串的内容在哪里?
我想要的是所有公共方法的数组,只有公共方法的数组,来自继承树中的最低类.例如:
class MyClass { }
class MyExtendedClass extends MyClass { }
class SomeOtherClass extends MyClass { }
Run Code Online (Sandbox Code Playgroud)
从MyClass的内部我想从MyExtendedClass和SomeOtherClass获取所有PUBLIC方法.
我发现我可以使用Reflection Class来做到这一点,但是当我这样做时,我也从MyClass获取方法,我不想得到它们:
$class = new ReflectionClass('MyClass');
$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?或者我在这种情况下唯一的解决方案是过滤掉反射类的结果?
我的应用程序可以根据数据库中的设置(文件,类和方法名称)动态加载dll.为了方便,加快和减少反射的使用,我想有一个缓存....
遵循使用的想法:
MethodInfo.Invoke
Run Code Online (Sandbox Code Playgroud)
没有任何表演(反映性能 - 创建代表(属性C#))我想翻译任何方法调用.我想到了一些像这样的东西:
public static T Create<T>(Type type, string methodName) // or
public static T Create<T>(MethodInfo info) // to use like this:
var action = Create<Action<object>>(typeof(Foo), "AnySetValue");
Run Code Online (Sandbox Code Playgroud)
一个要求是所有参数都可以是对象.
我正在尝试处理表达式,到目前为止我有这样的事情:
private void Sample()
{
var assembly = Assembly.GetAssembly(typeof(Foo));
Type customType = assembly.GetType("Foo");
var actionMethodInfo = customType.GetMethod("AnyMethod");
var funcMethodInfo = customType.GetMethod("AnyGetString");
var otherActionMethod = customType.GetMethod("AnySetValue");
var otherFuncMethodInfo = customType.GetMethod("OtherGetString");
var foo = Activator.CreateInstance(customType);
var actionAccessor = (Action<object>)BuildSimpleAction(actionMethodInfo);
actionAccessor(foo);
var otherAction = (Action<object, object>)BuildOtherAction(otherActionMethod);
otherAction(foo, string.Empty);
var otherFuncAccessor …Run Code Online (Sandbox Code Playgroud) 我有一个Foo有公共和受保护财产的课程. Foo需要有一个非静态方法,getPublicVars()它返回一个包含所有公共属性的列表Foo(这只是一个例子,我从外部知道Foo调用的对象get_object_vars()将完成这个并且不需要我的getPublicVars()方法).
注意:这还必须将在运行时分配的动态声明的属性返回给类的定义中未定义的类实例(对象).
这是一个例子:
class Foo{
private $bar = '123';
protect $boo = '456';
public $beer = 'yum';
//will return an array or comma seperated list
public function getPublicVars(){
// thar' be magic here...
}
}
$foo = new Foo();
$foo->tricky = 'dynamically added var';
$result = $foo->getPublicVars();
var_dump($result); // array or comma list with 'tricky' and 'beer'
Run Code Online (Sandbox Code Playgroud)
从类本身的方法中获取对象的唯一公共属性的最简洁方法是什么?public和protected都可见?
我看过:
但这似乎并没有解决我的问题,因为它指向get_object_vars()从对象外部使用.
我正在用C#和XAML编写Windows 8应用程序.我有一个类,它具有许多相同类型的属性,这些属性在构造函数中以相同的方式设置.而不是手动编写和分配每个属性我想获得我的类中的某些类型的所有属性的列表,并将它们全部设置为foreach.
在"普通".NET中我会写这个
var properties = this.GetType().GetProperties();
foreach (var property in properties)
{
if (property.PropertyType == typeof(Tuple<string,string>))
property.SetValue(this, j.GetTuple(property.Name));
}
Run Code Online (Sandbox Code Playgroud)
where j是我的构造函数的参数.在WinRT GetProperties()中不存在.Intellisense for this.GetType().没有显示我可以使用的任何有用的东西.
我有各种各样的方法,在继续自己的实现之前都需要执行相同的功能.现在我可以在每种方法中实现这些功能,但我想知道是否有办法利用它attributes来做到这一点?作为一个非常简单的示例,所有网络呼叫都必须检查网络连接.
public void GetPage(string url)
{
if(IsNetworkConnected())
...
else
...
}
Run Code Online (Sandbox Code Playgroud)
这可行,但我必须为IsNetworkConnected使用网络的每个方法调用该方法并单独处理它.相反,我想这样做
[NetworkCall]
public void GetPage(string url)
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果网络不可用,则会调用错误方法,但会GetPage被忽略,否则会GetPage被调用.
这听起来非常像Aspect Orientated Programming,但我不想为几个调用实现整个框架.这更像是一个学习练习而不是实现练习,所以我很好奇这样的事情是如何最好地实现的.
这是我的代码看起来如果我使用预定义的类:
List<MyClass> result = new ArrayList<MyClass>();
try {
Query query = mgr.newQuery(MyClass.class);
for(Object obj : (List<Object>) query.execute()) {
result.add(((MyClass) obj));
}
}
....
return result;
Run Code Online (Sandbox Code Playgroud)
现在我需要的是更通用的:从一个普通的类名称开始(作为一个字符串,即"TheChosenOne")我需要做同样的事情,但我无法弄清楚如何锻造部件应该做的..
只是为了举例说明我正在尝试做的事情:
String str = "TheChosenOne"; //this value may change
Class cls;
List<Object> result = new ArrayList<Object>();
try {
if(str.equals("TheChosenOne"))
cls = Class.forName("com.blabla.TheChosenOne");
else if(str.equals("Rabbit"))
cls = Class.forName("com.blabla.Rabbit");
else if(str.equals("Batman"))
cls = Class.forName("com.heroes.Batman");
else
cls = null;
if(cls != null){
Query query = mgr.newQuery(MyClass.class);
for(Object obj : (List<Object>) query.execute()) {
result.add(((???) obj)); //I need help …Run Code Online (Sandbox Code Playgroud) 根据JSR-133,不可变对象是线程安全的,不需要同步.但是,可以使用反射更新最终字段的值:
package com.stackoverflow;
import java.lang.reflect.Field;
public class WhatsGoingOn {
static class Immutable {
private final int value;
public Immutable(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
final Immutable immutable = new Immutable(Integer.MIN_VALUE);
final Field f = Immutable.class.getDeclaredField("value");
f.setAccessible(true);
System.out.println(immutable.getValue());
f.set(immutable, Integer.MAX_VALUE);
System.out.println(immutable.getValue());
}
}
Run Code Online (Sandbox Code Playgroud)
鉴于依赖于反射的框架数量(Spring和Hibernate只有少数),我很好奇规范说明了这个场景.例如,如果我将字段更新放入synchronized块中将保证其他线程中的可见性,或者值将根据spec的最终版本缓存在寄存器中.
http://download.oracle.com/otndocs/jcp/memory_model-1.0-pfd-spec-oth-JSpec/
我想知道是否可以确定Objects属性的类或基本类型.获取所有属性名称和值非常简单.所以回答
那么有什么方法可以获得属性类类型,而属性没有值或零值?
示例代码
@interface MyObject : NSObject
@property (nonatomic, copy) NSString *aString;
@property (nonatomic, copy) NSDate *aDate;
@property NSInteger aPrimitive;
@end
@implementation MyObject
@synthesize aString;
@synthesize aDate;
@synthesize aPrimitive;
- (void)getTheTypesOfMyProperties {
unsigned int count;
objc_property_t* props = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i++) {
objc_property_t property = props[i];
// Here I can easy get the name or value
const char * name = property_getName(property);
// But is there any magic function that …Run Code Online (Sandbox Code Playgroud) 我有一个使用Entity Framework的类库项目,它运行良好,直到我将模型移动到一个单独的类库类型项目.
在我将模型移到一个名为Model的单独的类库项目之后,我将app/web.config中的连接字符串更改为如下所示:
<add name="GlobalizationEntities"
connectionString="metadata=res://Model.dll/Models.ResourceGlobalizationModel.csdl|
res://Model.dll/Models.ResourceGlobalizationModel.ssdl|
res://Model.dll/Models.ResourceGlobalizationModel.msl;
provider=System.Data.SqlClient;
provider connection string="
Data Source=MyComputer\sqlexpress;
Initial Catalog=DaDatabase;
Integrated Security=true;
MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
Run Code Online (Sandbox Code Playgroud)
(为了便于阅读,我在上面的代码段中包含了换行符.我的代码没有这些换行符.)
现在,我的解决方案结构如下所示:

但是,我FileNotFound在运行时获得一个异常,其内容如下:
System.IO.FileNotFoundException was unhandled by user code
HResult=-2147024894
Message=Unable to resolve assembly 'Model.dll'.
Source=System.Data.Entity
StackTrace:
at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.ResolveAssemblyName(String assemblyName, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataCache.SplitPaths(String paths)
at System.Data.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections) …Run Code Online (Sandbox Code Playgroud) reflection ×10
c# ×4
java ×2
oop ×2
php ×2
.net ×1
aop ×1
architecture ×1
attributes ×1
casting ×1
class ×1
concurrency ×1
immutability ×1
jvm ×1
lambda ×1
objective-c ×1
string ×1