Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过反射完全实例化对象而不使用构造函数_C#_Reflection_Types_Initialization - Fatal编程技术网

C# 通过反射完全实例化对象而不使用构造函数

C# 通过反射完全实例化对象而不使用构造函数,c#,reflection,types,initialization,C#,Reflection,Types,Initialization,我找到的与这个问题相关的最接近的答案并没有真正帮助解决这个问题,尽管也许我在寻找这个问题时做得不好 现在,我想解决的是: 我想完整地填写并初始化一个对象,其中我只有类型,而这个对象没有构造函数,直到运行时我才知道它是什么类型 private readonly Dictionary<string, object> exampleDict = new Dictionary<string, string> { { "String", "\"String\"" }, { "

我找到的与这个问题相关的最接近的答案并没有真正帮助解决这个问题,尽管也许我在寻找这个问题时做得不好

现在,我想解决的是:

我想完整地填写并初始化一个对象,其中我只有类型,而这个对象没有构造函数,直到运行时我才知道它是什么类型

private readonly Dictionary<string, object> exampleDict = new Dictionary<string, string> { { "String", "\"String\"" }, { "Guid", Guid.NewGuid() }, { "Boolean", False }, { "int", 0 }, { "Decimal", 5.004 }, { "Int32", 0 }, { "Float", 10.01 }, { "Double", 0.101 } };
//Essentially a dictionary of what to init properties to
private object PopulateType(Type propertyType)
{
    object o = Activator.CreateInstance(propertyType);
    if(exampleDict.hasKey(propertyType.ToString())) //If it is in the dictionary, init it
        o = exampleDict[propertyType.Name];
    else
        foreach(var property in o.getProperties())//Otherwise look at each of its properties and init them to init the object
            PopulateType(typeof(property));
}
我想做的是打电话:

object newObject = PopulateType(typeof(ClassOne))

我事先不知道我将使用哪一个,也没有构造函数。我希望能够将
出生国
出生地
设置为“字符串”,如果它是
ClassOne
放入
PopulateType
,我希望能够设置
FirstName=“String”
LastName=“String”
出生地=新ClassOne{BirthCountry=“String”,BirthCity=“String”
但我希望能够为我碰巧拥有的任何类做到这一点(这些只是示例)

进一步编辑

我能够从类型生成基类。但我无法点击属性将它们设置为除null以外的任何值

编辑-在水果极客(非常感谢的朋友)的帮助下,我能够让程序工作

private object PopulateType(Type propertyType)
{
    object o = null;
    if (exampleDict.ContainsKey(propertyType.Name))
        o = exampleDict[propertyType.Name];
    else
    {
        var types = AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes()).Where(p => propertyType.IsAssignableFrom(p));
        try{o = Activator.CreateInstance(propertyType);}
        catch{o = Activator.CreateInstance(types.Last());}   
        foreach (PropertyInfo prop in o.GetType().GetProperties())
            try
            {
                prop.SetValue(o, PopulateType(prop.PropertyType), null);
            }
            catch (Exception){}
    }
    return o;
}

请注意,try/catch用于:如果接口未实现,则防止爆炸,并且不尝试实例化dicts/list/array(那些仍然需要工作)

您可以使用反射来检查属性是否存在并设置它

PopulateType(Object obj)
{
    //A dictionary of values to set for found properties
    Dictionary<String, Object> defaultValues = new Dictionary<String, Object>();
    defaultValues.Add("BirthPlace", "Amercia");
    for (var defaultValue in defaultValues)
    {
        //Here is an example that just set BirthPlace to a known value Amercia
        PropertyInfo prop = obj.GetType().GetProperty(defaultValue.Key, BindingFlags.Public | BindingFlags.Instance);
        if(null != prop && prop.CanWrite)
        {
            prop.SetValue(obj, defaultValue.Value, null);
        }
    }
}
PopulateType(对象对象对象)
{
//要为找到的属性设置的值字典
字典默认值=新字典();
默认值。添加(“出生地”、“美国”);
for(默认值中的var defaultValue)
{
//下面是一个将出生地设置为已知值Amercia的示例
PropertyInfo prop=obj.GetType().GetProperty(defaultValue.Key,BindingFlags.Public | BindingFlags.Instance);
if(null!=prop&&prop.CanWrite)
{
prop.SetValue(obj,defaultValue.Value,null);
}
}
}

您可以使用反射来检查属性是否存在并设置它

PopulateType(Object obj)
{
    //A dictionary of values to set for found properties
    Dictionary<String, Object> defaultValues = new Dictionary<String, Object>();
    defaultValues.Add("BirthPlace", "Amercia");
    for (var defaultValue in defaultValues)
    {
        //Here is an example that just set BirthPlace to a known value Amercia
        PropertyInfo prop = obj.GetType().GetProperty(defaultValue.Key, BindingFlags.Public | BindingFlags.Instance);
        if(null != prop && prop.CanWrite)
        {
            prop.SetValue(obj, defaultValue.Value, null);
        }
    }
}
PopulateType(对象对象对象)
{
//要为找到的属性设置的值字典
字典默认值=新字典();
默认值。添加(“出生地”、“美国”);
for(默认值中的var defaultValue)
{
//下面是一个将出生地设置为已知值Amercia的示例
PropertyInfo prop=obj.GetType().GetProperty(defaultValue.Key,BindingFlags.Public | BindingFlags.Instance);
if(null!=prop&&prop.CanWrite)
{
prop.SetValue(obj,defaultValue.Value,null);
}
}
}


那么你想在运行时构造一个类型(设置它有哪些成员)?我会详细编辑它。别忘了,如果你不在代码中定义任何构造函数,你会得到一个自动的无参数构造函数,你可以通过反射调用。好的一点-我不是说它没有构造函数周期,但更重要的是,我没有一个构造函数来设置属性,所以我还没有找到一种方法来设置这些属性。有人能告诉我为什么我被否决吗?如果我做错了什么,我不想再这样做:)那么你想在运行时构造一个类型(设置它有哪些成员)吗?我会用更多的细节来编辑它。别忘了,如果你不在代码中定义任何构造函数,你得到了一个可以通过反射调用的自动无参数构造函数。好的一点-我不是说它没有构造函数周期,而是说我没有一个可以设置属性的构造函数-所以我无法找到设置这些属性的方法。有人能给我解释一下为什么我被否决吗?如果我做错了什么,我宁愿不要再这样做:)你是把它投给(我的班级)-我想我的编辑让它变得更不清楚,但我更想说的是我不知道到底发生了什么。它可以是ClassOne,也可以是ClassTwo,但我不知道,而且它们不会覆盖或固有于任何公共源。你的问题是你想创建一个实例而不调用构造函数。你真的只是想弄清楚如何使用反射在对象上设置属性吗?本质上,是的-我想创建一个实例,而不调用构造函数(或者调用空的构造函数,没关系),然后使用reflectionUpdated answer填充/创建该对象的每个属性的实例。您想使用反射设置属性。+1。请注意,试图通过反射水合物对象可能不需要在GealReal案中创建工作对象-考虑一些类似于Socket或FielestRAM-没有任何设置属性会使对象实际上有用。你正在将它投射到(MyC类)-我想我的编辑使它更不清楚,但我更多的意思是我不知道到底发生了什么。它可以是ClassOne,也可以是ClassTwo,但我不知道,而且它们不会覆盖或固有于任何公共源。你的问题是你想创建一个实例而不调用构造函数。你真的只是想弄清楚如何使用反射在对象上设置属性吗?本质上,是的-我想创建一个实例,而不调用构造函数(或者调用空的构造函数,没关系),然后使用reflectionUpdated answer填充/创建该对象的每个属性的实例。您想使用反射设置属性。+1。注意,试图通过反射水合物对象可能不需要在GealReal案中创建工作对象-考虑一些类似于Socket或FielestRAM-没有任何设置属性会使对象实际上有用。
PopulateType(Object obj)
{
    //A dictionary of values to set for found properties
    Dictionary<String, Object> defaultValues = new Dictionary<String, Object>();
    defaultValues.Add("BirthPlace", "Amercia");
    for (var defaultValue in defaultValues)
    {
        //Here is an example that just set BirthPlace to a known value Amercia
        PropertyInfo prop = obj.GetType().GetProperty(defaultValue.Key, BindingFlags.Public | BindingFlags.Instance);
        if(null != prop && prop.CanWrite)
        {
            prop.SetValue(obj, defaultValue.Value, null);
        }
    }
}