本文整理汇总了C#中Type.GetConstructor方法的典型用法代码示例。如果您正苦于以下问题:C# Type.GetConstructor方法的具体用法?C# Type.GetConstructor怎么用?C# Type.GetConstructor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Type
的用法示例。
在下文中一共展示了Type.GetConstructor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SerializableImplementor
internal SerializableImplementor(EntityType ospaceEntityType)
{
_baseClrType = ospaceEntityType.ClrType;
_baseImplementsISerializable = _baseClrType.IsSerializable && typeof(ISerializable).IsAssignableFrom(_baseClrType);
if (_baseImplementsISerializable)
{
// Determine if interface implementation can be overridden.
// Fortunately, there's only one method to check.
var mapping = _baseClrType.GetInterfaceMap(typeof(ISerializable));
_getObjectDataMethod = mapping.TargetMethods[0];
// Members that implement interfaces must be public, unless they are explicitly implemented, in which case they are private and sealed (at least for C#).
var canOverrideMethod = (_getObjectDataMethod.IsVirtual && !_getObjectDataMethod.IsFinal) && _getObjectDataMethod.IsPublic;
if (canOverrideMethod)
{
// Determine if proxied type provides the special serialization constructor.
// In order for the proxy class to properly support ISerializable, this constructor must not be private.
_serializationConstructor =
_baseClrType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);
_canOverride = _serializationConstructor != null
&&
(_serializationConstructor.IsPublic || _serializationConstructor.IsFamily
|| _serializationConstructor.IsFamilyOrAssembly);
}
Debug.Assert(
!(_canOverride && (_getObjectDataMethod == null || _serializationConstructor == null)),
"Both GetObjectData method and Serialization Constructor must be present when proxy overrides ISerializable implementation.");
}
}
示例2: CreateDefaultConstructorDelegate
/// <summary>
/// Creates the default constructor delegate.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>a <see cref="DefaultCreatorDelegate"/></returns>
/// <exception cref="Exception"><c>Exception</c>.</exception>
public static DefaultCreatorDelegate CreateDefaultConstructorDelegate(Type type)
{
ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[0],
null);
if (constructorInfo == null)
{
throw new Exception(
string.Format(
"The type {0} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).",
type));
}
#if !CompactFramework
DynamicMethod dynamicMethod = new DynamicMethod("InstantiateObject",
MethodAttributes.Static | MethodAttributes.Public,
CallingConventions.Standard,
typeof(object),
null,
type,
true);
ILGenerator generator = dynamicMethod.GetILGenerator();
generator.Emit(OpCodes.Newobj, constructorInfo);
generator.Emit(OpCodes.Ret);
return (DefaultCreatorDelegate)dynamicMethod.CreateDelegate(typeof(DefaultCreatorDelegate));
#else
return () => constructorInfo.Invoke(null);
#endif
}
示例3: BindType
public string wrapName = ""; //产生的wrap文件名字
#endregion Fields
#region Constructors
public BindType(Type t)
{
type = t;
name = ToLuaExport.GetTypeStr(t);
if (t.IsGenericType) {
libName = ToLuaExport.GetGenericLibName(t);
wrapName = ToLuaExport.GetGenericLibName(t);
} else {
libName = t.FullName.Replace("+", ".");
wrapName = name.Replace('.', '_');
if (name == "object") {
wrapName = "System_Object";
}
}
if (t.BaseType != null) {
baseName = ToLuaExport.GetTypeStr(t.BaseType);
if (baseName == "ValueType") {
baseName = null;
}
}
if (t.GetConstructor(Type.EmptyTypes) == null && t.IsAbstract && t.IsSealed) {
baseName = null;
IsStatic = true;
}
}
示例4: LoadConfig
public static Dictionary<int, BaseConfig> LoadConfig(string path, Type type)
{
int jsonStartIndex = 4;
int columnStartIndex = 1;
var ta = Resources.Load(path) as TextAsset;
string RawJson = ta.text;
Dictionary<int, BaseConfig> dic = new Dictionary<int, BaseConfig>();
TabFileReader tabReader = new TabFileReader();
tabReader.Load(RawJson);
int JsonNodeCount = tabReader.RowCount;
for (int i = jsonStartIndex; i < JsonNodeCount; i++)
{
try
{
System.Reflection.ConstructorInfo conInfo = type.GetConstructor(Type.EmptyTypes);
BaseConfig t = conInfo.Invoke(null) as BaseConfig;
t.init(tabReader, i, columnStartIndex);
if (0 != t.id)
{
if (!dic.ContainsKey(t.id))
dic.Add(t.id, t);
else
Log.LogError("Config Data Ready Exist, TableName: " + t.GetType().Name + " ID:" + t.id);
}
}
catch (Exception)
{
Log.LogError(type.ToString() + " ERROR!!! line " + (i + 2).ToString());
}
}
return dic;
}
示例5: EarlyBoundInfo
private ConstructorInfo constrInfo; // Constructor for the early bound function object
public EarlyBoundInfo(string namespaceUri, Type ebType) {
Debug.Assert(namespaceUri != null && ebType != null);
// Get the default constructor
this.namespaceUri = namespaceUri;
this.constrInfo = ebType.GetConstructor(Type.EmptyTypes);
Debug.Assert(this.constrInfo != null, "The early bound object type " + ebType.FullName + " must have a public default constructor");
}
示例6: GetFactory
/// <summary>
/// Gets factory to create instance of type using the public parameterless ctor.
/// Use it when you want to create many instances of the same type in different objects
/// Aprox, 1.3x faster than Activator, almost as fast a manual if you cache and reuse the delegate
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static Func<object> GetFactory(Type t)
{
Func<object> inv;
lock (actLock)
{
if (_actCache == null) _actCache = new Dictionary<Type, Func<object>>();
if (!_actCache.TryGetValue(t,out inv))
{
var constructor = t.GetConstructor(Type.EmptyTypes)?? t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
var body = Expression.New(constructor);
inv = Expression.Lambda<Func<object>>(body).Compile();
_actCache[t] = inv;
}
}
return inv;
}
示例7: CreateObject
private static object CreateObject(Type Type)
{
// create object
ConstructorInfo Constructor = Type.GetConstructor(Type.EmptyTypes);
if(Constructor == null)
throw new Exception("Type '" + Type + "' has no public constructor without arguments");
object Result = Constructor.Invoke(new object[] {});
return Result;
}
示例8: Properties
public void Properties(Type type, Type[] typeParameters)
{
ConstructorInfo constructor = type.GetConstructor(typeParameters);
Assert.Equal(type, constructor.DeclaringType);
Assert.Equal(type.GetTypeInfo().Module, constructor.Module);
Assert.Equal(ConstructorInfo.ConstructorName, constructor.Name);
Assert.True(constructor.IsConstructor);
Assert.Equal(MemberTypes.Constructor, constructor.MemberType);
}
示例9: CreateInstance
public static object CreateInstance(Type dataType)
{
var info = dataType.GetConstructor(new Type[0]);
if (info == null)
throw new NotSupportedException("The type does not have a constructor without any parameters");
if (!info.IsPublic)
throw new Exception("The type does not have a public constructor without any parameters");
return info.Invoke(new object[0]);
}
示例10: ActivityCodeGeneratorAttribute
public ActivityCodeGeneratorAttribute(Type codeGeneratorType)
{
if (codeGeneratorType == null)
throw new ArgumentNullException("codeGeneratorType");
if (!typeof(ActivityCodeGenerator).IsAssignableFrom(codeGeneratorType))
throw new ArgumentException(SR.GetString(SR.Error_NotCodeGeneratorType), "codeGeneratorType");
if (codeGeneratorType.GetConstructor(new Type[0] { }) == null)
throw new ArgumentException(SR.GetString(SR.Error_MissingDefaultConstructor, codeGeneratorType.FullName), "codeGeneratorType");
this.codeGeneratorTypeName = codeGeneratorType.AssemblyQualifiedName;
}
示例11: TryDeserialize
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType)
{
if (instance == null)
instance = storageType.GetConstructor(Type.EmptyTypes).Invoke(null);
var myType = (ModeMatch3PlaygroundSavedata)instance;
var dataItems = data.AsList;
myType.CurrentPlaygroundTime = (float)dataItems[0].AsDouble;
myType.Score = (Int32)dataItems[1].AsInt64;
myType.Difficulty = (DifficultyLevel)dataItems[2].AsInt64;
if (dataItems[3].IsList)
{
var list = dataItems[3].AsList;
if (list != null && list.Count != 0)
{
myType.Items = new GameItemType[list.Count][];
for (var i = 0; i < list.Count; i++)
{
var localList = list[i].AsList;
myType.Items[i] = localList.Select(lli => (GameItemType) lli.AsInt64).ToArray();
}
}
}
if (dataItems[4].IsList)
{
var list2 = dataItems[4].AsList;
if (list2 != null && list2.Count != 0)
{
myType.MovingTypes = new GameItemMovingType[list2.Count][];
for (var i = 0; i < list2.Count; i++)
{
var localList2 = list2[i].AsList;
myType.MovingTypes[i] = localList2.Select(lli => (GameItemMovingType)lli.AsInt64).ToArray();
}
}
}
if (!dataItems[5].IsList) return fsResult.Success;
var progressBarData = dataItems[5].AsList;
if (myType.ProgressBarStateData == null)
myType.ProgressBarStateData = new ProgressBarState();
myType.ProgressBarStateData.Multiplier = (float)progressBarData[0].AsDouble;
myType.ProgressBarStateData.Upper = (float)progressBarData[1].AsDouble;
myType.ProgressBarStateData.State = (float)progressBarData[2].AsDouble;
return fsResult.Success;
}
示例12: CheckSerializableType
public static void CheckSerializableType (Type type, bool allowPrivateConstructors)
{
if (type.IsArray) return;
#if NET_2_0
if (!allowPrivateConstructors && type.GetConstructor (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, empty_modifiers) == null && !type.IsAbstract && !type.IsValueType)
#else
if (!allowPrivateConstructors && type.GetConstructor (Type.EmptyTypes) == null && !type.IsAbstract && !type.IsValueType)
#endif
throw new InvalidOperationException (type.FullName + " cannot be serialized because it does not have a default public constructor");
if (type.IsInterface && !TypeTranslator.GetTypeData (type).IsListType)
throw new InvalidOperationException (type.FullName + " cannot be serialized because it is an interface");
Type t = type;
Type oldt = null;
do {
if (!t.IsPublic && !t.IsNestedPublic)
throw new InvalidOperationException (type.FullName + " is inaccessible due to its protection level. Only public types can be processed");
oldt = t;
t = t.DeclaringType;
}
while (t != null && t != oldt);
}
示例13: PrivateObjectTester
private Type type; // type of class to manage
#endregion Fields
#region Constructors
public PrivateObjectTester(string qualifiedTypeName, params object[] args)
{
perm = new ReflectionPermission(PermissionState.Unrestricted);
perm.Demand();
type = Type.GetType(qualifiedTypeName);
Type[] types = new Type[args.Length];
for (int i=0; i < args.Length; i++)
{
types[i] = args[i].GetType();
}
ConstructorInfo constructor = type.GetConstructor(bindingFlags,null,types,null);
instance =constructor.Invoke(args);
}
示例14: InitType
public static void InitType() {
if (realType == null) {
Assembly assembly = Assembly.GetAssembly(typeof(Editor));
realType = assembly.GetType("UnityEditor.AvatarPreview");
method_ctor = realType.GetConstructor(new Type[] { typeof(Animator), typeof(Motion)});
property_OnAvatarChangeFunc = realType.GetProperty("OnAvatarChangeFunc");
property_IKOnFeet = realType.GetProperty("IKOnFeet");
property_Animator = realType.GetProperty("Animator");
method_DoPreviewSettings = realType.GetMethod("DoPreviewSettings");
method_OnDestroy = realType.GetMethod("OnDestroy");
method_DoAvatarPreview = realType.GetMethod("DoAvatarPreview", new Type[] {typeof(Rect), typeof(GUIStyle)});
method_ResetPreviewInstance = realType.GetMethod("ResetPreviewInstance");
// method_CalculatePreviewGameObject = realType.GetMethod("CalculatePreviewGameObject", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
field_timeControl = realType.GetField("timeControl");
}
}
示例15: CheckSerializableType
public static void CheckSerializableType (Type type)
{
if (type.IsArray) return;
if (type.GetConstructor (Type.EmptyTypes) == null && !type.IsAbstract && !type.IsValueType)
throw new InvalidOperationException (type.FullName + " cannot be serialized because it does not have a default public constructor");
if (type.IsInterface)
throw new InvalidOperationException (type.FullName + " cannot be serialized because it is an interface");
Type t = type;
do {
if (!t.IsPublic && !t.IsNestedPublic)
throw new InvalidOperationException (type.FullName + " is inaccessible due to its protection level. Only public types can be processed");
t = t.DeclaringType;
}
while (t != null);
}