本文整理汇总了C#中System.Type.IsAssignableFrom方法的典型用法代码示例。如果您正苦于以下问题:C# Type.IsAssignableFrom方法的具体用法?C# Type.IsAssignableFrom怎么用?C# Type.IsAssignableFrom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Type
的用法示例。
在下文中一共展示了Type.IsAssignableFrom方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InternalConvert
static object InternalConvert(object arg, Type source, Type target, bool isAddress)
{
if (target == source)
return arg;
if (target.IsValueType)
{
if (source.IsValueType)
{
if (!CanConvert (Type.GetTypeCode (target)))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.NoConversionPossibleTo, DataContract.GetClrTypeFullName(target))));
else
return target;
}
else if (source.IsAssignableFrom(target))
return arg;
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
else if (target.IsAssignableFrom(source))
return arg;
else if (source.IsAssignableFrom(target))
return arg;
else if (target.IsInterface || source.IsInterface)
return arg;
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
示例2: Aggregate
/// <summary>
/// Get a function that coerces a sequence of one type into another type.
/// This is primarily used for aggregators stored in ProjectionExpression's,
/// which are used to represent the final transformation of the entire result set of a query.
/// </summary>
public static LambdaExpression Aggregate(Type expectedType, Type actualType)
{
Type actualElementType = actualType.GetSequenceElementType();
if (!expectedType.IsAssignableFrom(actualType))
{
Type expectedElementType = expectedType.GetSequenceElementType();
ParameterExpression p = Expression.Parameter(actualType, "p");
Expression body = null;
if (expectedType.IsAssignableFrom(actualElementType))
body = Expression.Call(typeof(Enumerable), "SingleOrDefault", new Type[] { actualElementType }, p);
else if (expectedType.IsGenericType && expectedType.GetGenericTypeDefinition() == typeof(IQueryable<>))
body = Expression.Call(typeof(Queryable), "AsQueryable", new Type[] { expectedElementType },
CoerceElement(expectedElementType, p));
else if (expectedType.IsArray && expectedType.GetArrayRank() == 1)
body = Expression.Call(typeof(Enumerable), "ToArray", new Type[] { expectedElementType },
CoerceElement(expectedElementType, p));
else if (expectedType.IsAssignableFrom(typeof(List<>).MakeGenericType(actualElementType)))
body = Expression.Call(typeof(Enumerable), "ToList", new Type[] { expectedElementType },
CoerceElement(expectedElementType, p));
else
{
ConstructorInfo ci = expectedType.GetConstructor(new Type[] { actualType });
if (ci != null)
body = Expression.New(ci, p);
}
if (body != null)
return Expression.Lambda(body, p);
}
return null;
}
示例3: CanReadFile
public bool CanReadFile (FilePath file, Type expectedObjectType)
{
if (expectedObjectType.IsAssignableFrom (typeof(Solution)) && String.Compare (file.Extension, ".sln", true) == 0) {
string ver = GetSlnFileVersion (file);
if (ver == "7.00" || ver == "8.00")
return true;
}
if (!expectedObjectType.IsAssignableFrom (typeof(DotNetProject)))
return false;
if (String.Compare (file.Extension, ".csproj", true) != 0 &&
String.Compare (file.Extension, ".vbproj", true) != 0)
return false;
try {
using (XmlReader xr = XmlReader.Create (file)) {
xr.MoveToContent ();
if (xr.NodeType == XmlNodeType.Element && String.Compare (xr.LocalName, "VisualStudioProject") == 0)
return true;
}
} catch {
return false;
}
return false;
}
示例4: CreateFromString
private object CreateFromString(Type targetType,string name)
{
object instance = null;
if (FrameworkElement != null)
{
instance = FrameworkElement.FindResource(name);
if (instance != null && targetType.IsAssignableFrom(instance.GetType())) return instance;
instance = null;
}
if(Contains(name))
{
instance = this[name];
if (instance != null && targetType.IsAssignableFrom(instance.GetType())) return instance;
instance = null;
}
if (!RequireExactMatch)
{
foreach (string key in Keys)
{
if (key.Contains(name))
{
instance = this[key];
if (instance != null && targetType.IsAssignableFrom(instance.GetType())) return instance;
}
}
}
return null;
}
示例5: CreateInstances
public override IEnumerable<TestCaseParameter> CreateInstances(Type targetType)
{
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
foreach (MethodInfo method in ReflectionHelper.GetMethods(this.FactoryType, typeof(FactoryAttribute)))
{
if (method.GetParameters().Length > 0)
continue;
FactoryAttribute factoryAttribute = ReflectionHelper.GetAttribute<FactoryAttribute>(method);
// the method returns the type or a enumerable collection
if (targetType.IsAssignableFrom(method.ReturnType))
yield return CreateSingleInstance(method);
else if (
targetType.IsAssignableFrom(typeof(IEnumerable<>).MakeGenericType(targetType))
|| (
targetType.IsAssignableFrom(typeof(IEnumerable))
&& targetType.IsAssignableFrom(factoryAttribute.FactoredType)
)
)
{
foreach (TestCaseParameter parameter in CreateMultipleInstances(method))
yield return parameter;
}
}
}
示例6: GetActualType
public Type GetActualType(Type type, IAdviceRequester adviceRequester)
{
Type result = null;
if (type != null)
{
if (type != typeof(string))
{
if (!typeof(IDictionary).IsAssignableFrom(type) &&
(!type.IsGenericType || type.GetGenericArguments().Length != 2 || !typeof(IDictionary<,>).MakeGenericType(type.GetGenericArguments()).IsAssignableFrom(type)))
{
if (type.IsClass && typeof(IEnumerable).IsAssignableFrom(type))
result = type;
else
{
if (type.IsInterface && type.IsAssignableFrom(typeof(List<object>)))
result = typeof(List<object>);
else
{
if (type.IsGenericType && type.GetGenericArguments().Length == 1 && type.IsAssignableFrom(typeof(List<>).MakeGenericType(type.GetGenericArguments())))
result = typeof(List<>).MakeGenericType(type.GetGenericArguments());
}
}
}
}
}
if (_log.IsDebugEnabled)
_log.Debug("Converted '" + type + "' to '" + result + "'.");
return result;
}
示例7: CreateViewModelConfig
public ViewModelConfig CreateViewModelConfig(Type type)
{
if (!type.IsBaseObject() && !type.IsDefined(typeof(ComplexTypeAttribute))) return null;
string serviceName = "";
if (type.IsBaseObject())
{
if (type.IsAssignableFrom(typeof(HCategory)))
serviceName = typeof(IBaseCategoryService<>).GetTypeName();
else if (type.IsAssignableFrom(typeof(ICategorizedItem)))
serviceName = typeof(IBaseCategorizedItemService<>).GetTypeName();
else
serviceName = typeof(IBaseObjectService<>).GetTypeName();
}
return new ViewModelConfig(
mnemonic: type.GetTypeName(),
entity: type.GetTypeName(),
listView: new ListView(),
detailView: new DetailView(),
lookupProperty:
type.IsBaseObject()
? (type.GetProperty("Title") ?? type.GetProperty("Name") ?? type.GetProperty("ID")).Name
: "",
service: serviceName);
}
示例8: Copy
/// <summary>
/// Copies the specified source.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
/// <param name="type">The type the source and target should be interpreded as.</param>
/// <param name="progressDelegate">The progress delegate.</param>
public static void Copy(ICopy source, ICopy target, Type type, CopyToProgress progressDelegate)
{
if (!(type.IsAssignableFrom(source.GetType()) && type.IsAssignableFrom(target.GetType())))
throw new ArgumentException("Source and Target must implement " + type.ToString());
foreach (PropertyInfo info in type.GetProperties())
{
if (type.GetProperty(info.Name).IsDefined(typeof(IgnoreCopyAttribute), true) ||
source.GetType().GetProperty(info.Name).IsDefined(typeof(IgnoreCopyAttribute), true) ||
target.GetType().GetProperty(info.Name).IsDefined(typeof(IgnoreCopyAttribute), true))
continue;
if (typeof(ICopy).IsAssignableFrom(info.PropertyType))
{
ICopy copyObject = (info.GetValue(source, null) as ICopy);
if (copyObject != null)
copyObject.CopyTo(info.GetValue(target, null) as ICopy, progressDelegate);
}
if (info.IsDefined(typeof(ValueCopyAttribute), true))
{
object value = info.GetValue(source, null);
if (value != null)
info.SetValue(target, value, null);
}
}
}
示例9: Handle_error
public void Handle_error(string id_, string jwtResponse, Type expectedExceptionType, int expectedCode, int expectedStatus, string expectedMessage, string expectedDeveloperMessage)
{
var testApiKey = ClientApiKeys.Builder()
.SetId("2EV70AHRTYF0JOA7OEFO3SM29")
.SetSecret("goPUHQMkS4dlKwl5wtbNd91I+UrRehCsEDJrIrMruK8")
.Build();
var fakeRequestExecutor = Substitute.For<IRequestExecutor>();
fakeRequestExecutor.ApiKey.Returns(testApiKey);
this.dataStore = TestDataStore.Create(fakeRequestExecutor, Caches.NewInMemoryCacheProvider().Build());
var request = new DefaultHttpRequest(HttpMethod.Get, new CanonicalUri($"https://foo.bar?{IdSiteClaims.JwtResponse}={jwtResponse}"));
IIdSiteSyncCallbackHandler callbackHandler = new DefaultIdSiteSyncCallbackHandler(this.dataStore, request);
try
{
var accountResult = callbackHandler.GetAccountResult();
throw new Exception("Should not reach here. Proper exception was not thrown.");
}
catch (IdSiteRuntimeException e) when (expectedExceptionType.IsAssignableFrom(e.GetType()))
{
e.Code.ShouldBe(expectedCode);
e.HttpStatus.ShouldBe(expectedStatus);
e.Message.ShouldBe(expectedMessage);
e.DeveloperMessage.ShouldBe(expectedDeveloperMessage);
}
catch (Exception e) when (expectedExceptionType.IsAssignableFrom(e.GetType()))
{
e.Message.ShouldStartWith(expectedMessage);
}
}
开发者ID:ssankar1234,项目名称:stormpath-sdk-dotnet,代码行数:33,代码来源:DefaultIdSiteSyncCallbackHandler_exception_tests.cs
示例10: GetAppropriateViewModel
public static ValueViewModel GetAppropriateViewModel(Type PropertyType, Object ValueObject)
{
if (PropertyType.IsAssignableFrom(typeof (int))) return new IntValueViewModel(ValueObject);
if (PropertyType.IsAssignableFrom(typeof (bool))) return new BooleanValueViewModel(ValueObject);
if (PropertyType.IsAssignableFrom(typeof (string))) return new StringValueViewModel(ValueObject);
throw new ApplicationException("Не поддерживаемый для редактирования тип свойства!");
}
示例11: GetAggregator
/// <summary>
/// Get a function that coerces a sequence of one type into another type.
/// This is primarily used for aggregators stored in ProjectionExpression's, which are used to represent the
/// final transformation of the entire result set of a query.
/// </summary>
public static LambdaExpression GetAggregator(Type expectedType, Type actualType)
{
Type actualElementType = TypeHelper.GetElementType(actualType);
if (!expectedType.IsAssignableFrom(actualType))
{
Type expectedElementType = TypeHelper.GetElementType(expectedType);
ParameterExpression p = Expression.Parameter(actualType, "p");
Expression body = null;
if (expectedType.IsAssignableFrom(actualElementType))
{
body = Expression.Call(typeof(Enumerable), "SingleOrDefault", new Type[] { actualElementType }, p);
}
else if (expectedType.IsGenericType
&&
(expectedType == typeof(IQueryable) || expectedType == typeof(IOrderedQueryable)
|| expectedType.GetGenericTypeDefinition() == typeof(IQueryable<>)
|| expectedType.GetGenericTypeDefinition() == typeof(IOrderedQueryable<>)))
{
body = Expression.Call(
typeof(Queryable), "AsQueryable", new Type[] { expectedElementType }, CoerceElement(expectedElementType, p));
if (body.Type != expectedType)
{
body = Expression.Convert(body, expectedType);
}
}
else if (expectedType.IsArray && expectedType.GetArrayRank() == 1)
{
body = Expression.Call(
typeof(Enumerable), "ToArray", new Type[] { expectedElementType }, CoerceElement(expectedElementType, p));
}
else if (expectedType.IsGenericType && expectedType.GetGenericTypeDefinition().IsAssignableFrom(typeof(IList<>)))
{
var gt = typeof(DeferredList<>).MakeGenericType(expectedType.GetGenericArguments());
var cn =
gt.GetConstructor(new Type[] { typeof(IEnumerable<>).MakeGenericType(expectedType.GetGenericArguments()) });
body = Expression.New(cn, CoerceElement(expectedElementType, p));
}
else if (expectedType.IsAssignableFrom(typeof(List<>).MakeGenericType(actualElementType)))
{
// List<T> can be assigned to expectedType
body = Expression.Call(
typeof(Enumerable), "ToList", new Type[] { expectedElementType }, CoerceElement(expectedElementType, p));
}
else
{
// some other collection type that has a constructor that takes IEnumerable<T>
ConstructorInfo ci = expectedType.GetConstructor(new Type[] { actualType });
if (ci != null)
{
body = Expression.New(ci, p);
}
}
if (body != null)
{
return Expression.Lambda(body, p);
}
}
return null;
}
示例12: ReadFile
public object ReadFile(FilePath file, Type expectedType, IProgressMonitor monitor)
{
if (expectedType.IsAssignableFrom(typeof(WorkspaceItem)))
return DubFileManager.Instance.LoadAsSolution(file, monitor);
if (expectedType.IsAssignableFrom(typeof(SolutionEntityItem)))
return DubFileManager.Instance.LoadProject(file, Ide.IdeApp.Workspace.GetAllSolutions().First(), monitor);
return null;
}
示例13: GetTypesAssignableFrom
/// <summary>
/// Gets an array of <see cref="Type"/>s that are assignable from the given type with the
/// specified <see cref="IDefinitionManager"/>.
/// </summary>
/// <param name="type">The <see cref="System.Type"/> to find other types that are
/// assignable from this type.</param>
/// <returns>An array of <see cref="Type"/>s which the given type is assignable from.</returns>
public static Type[] GetTypesAssignableFrom(this IDefinitionManager definitions, Type type)
{
Type[] result = definitions.GetDefinitions()
.Where(definition => type.IsAssignableFrom(definition.ItemType)
&& type.IsAssignableFrom(definition.ItemType))
.Select(definition => definition.ItemType)
.ToArray();
return result;
}
示例14: GetAllTypesImplementingOpenGenericType
public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(this Assembly assembly, Type openGenericType)
{
return from type in assembly.GetExportedTypes()
from z in type.GetInterfaces()
let y = type.BaseType
where
(y != null && y.IsGenericType && openGenericType.IsAssignableFrom(y.GetGenericTypeDefinition())) ||
(z.IsGenericType && openGenericType.IsAssignableFrom(z.GetGenericTypeDefinition()))
select type;
}
示例15: CanReadFile
public bool CanReadFile (FilePath file, Type expectedType)
{
string ext = Path.GetExtension (file).ToLower ();
if (ext == ".mds" && expectedType.IsAssignableFrom (typeof(Solution)))
return true;
else if (ext == ".mdp" && expectedType.IsAssignableFrom (typeof(Project)))
return true;
else if (ext == ".mdw" && expectedType.IsAssignableFrom (typeof(WorkspaceItem)))
return true;
return ext == ".mdse" && expectedType.IsAssignableFrom (typeof(SolutionEntityItem));
}