Dynamically create an object of <Type>
This link should help:
https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance
Activator.CreateInstance will create an instance of the specified type.
You could wrap that in a generic method like this:
public T GetInstance<T>(string type)
{
return (T)Activator.CreateInstance(Type.GetType(type));
}
How to create own dynamic type or dynamic object in C#?
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.Number = 12;
MyDynamic.MyMethod = new Func<int>(() =>
{
return 55;
});
Console.WriteLine(MyDynamic.MyMethod());
Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.
Creating object with dynamic keys
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
Better way to Dynamically Create New Objects in JavaScript?
Assuming I understand your desire (and I'm not sure that I do) you can use the global window
object in DOM 0 browsers, or create your own reference to the global scope, and use that to look up variables defined locally.
var $global = this;
var firstObject = function(){};
var objName = "firstObject";
var instance = new $global[objName];
How do I dynamically assign properties to an object in TypeScript?
Index types
It is possible to denote obj
as any
, but that defeats the whole purpose of using typescript. obj = {}
implies obj
is an Object
. Marking it as any
makes no sense. To accomplish the desired consistency an interface could be defined as follows.
interface LooseObject {
[key: string]: any
}
var obj: LooseObject = {};
OR to make it compact:
var obj: {[k: string]: any} = {};
LooseObject
can accept fields with any string as key and any
type as value.
obj.prop = "value";
obj.prop2 = 88;
The real elegance of this solution is that you can include typesafe fields in the interface.
interface MyType {
typesafeProp1?: number,
requiredProp1: string,
[key: string]: any
}
var obj: MyType ;
obj = { requiredProp1: "foo"}; // valid
obj = {} // error. 'requiredProp1' is missing
obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number
obj.prop = "value";
obj.prop2 = 88;
Record<Keys,Type>
utility type
Update (August 2020): @transang brought this up in comments
Record<Keys,Type>
is a Utility type in typescript. It is a much cleaner alternative for key-value pairs where property-names are not known.
It's worth noting thatRecord<Keys,Type>
is a named alias to{[k: Keys]: Type}
whereKeys
andType
are generics.
IMO, this makes it worth mentioning here
For comparison,
var obj: {[k: string]: any} = {};
becomes
var obj: Record<string,any> = {}
MyType
can now be defined by extending Record type
interface MyType extends Record<string,any> {
typesafeProp1?: number,
requiredProp1: string,
}
While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.
Create dynamic instance from a dictionary of types
You can use Activator.CreateInstance
to create new objects of a particular type:
var type = types[itemName];
var item = Activator.CreateInstance(type);
However, I would suggest a slightly different approach. Instead of a dictionary containing types, make it a list of Func
s that give you the actual type. It's type-safe and has compile-time safety. For example:
var types = new Dictionary<string, Func<ItemClass>>()
{
{ "Weapon", () => new WeaponClass() },
{ "Consumable", () => new ConsumableClass() },
{ "Resource", () => new ResourceClass() }
};
Now your method can be:
public ItemClass CreateItem(string itemName)
{
if(types.TryGetValue(nameOfType, out var factory))
{
return factory();
}
throw new Exception("Er, no idea what that type is");
}
Create dynamic object from given class reference and add values from list to it
You could call the GetProperty
method of the type to get a PropertyInfo
and then call the SetValue
method of this one to set the property of a specific instance, e.g.:
public void CreateClassInstance<T>()
{
Type ReceiveClasstype = typeof(T);
T newObject = (T)Activator.CreateInstance(typeof(T));
//set the CollarId property of newObject:
var property = ReceiveClasstype.GetProperty("CollarID ");
property.SetValue(newObject, "collar id value...");
}
Of course you will need to know the name of the property that you want to set.
You could get the PropertyInfo
of all public properties of a type using the GetProperties
method:
PropertyInfo[] propertInfos = ReceiveClasstype.GetProperties();
Related Topics
C++ Const Keyword - Use Liberally
Getting the Current Time (In Milliseconds) from the System Clock in Windows
How Does Q_Foreach (= Foreach) MACro Work and Why Is It That Complex
What Is Allowed in a Constexpr Function
Dropping Privileges in C++ on Windows
Fast Implementation of Trigonometric Functions for C++
Cmake Simple Config File Example
How to Do Aes Decryption Using Openssl
Does Scopeguard Use Really Lead to Better Code
Purpose of Explicit Default Constructors
Vector: Initialization or Reserve
How to Declare Array with Auto
C++ Stack Trace from Unhandled Exception
Why am I Not Provided with a Default Copy Constructor from a Volatile
How to Build a Full Path String (Safely) from Separate Strings