Начиная с Java 7 (или Android API Level 21 = 5.0+) вы можете напрямую использовать ThreadLocalRandom.current().nextLong(n)
(для 0 ≤ x & lt; n) и ThreadLocalRandom.current().nextLong(m, n)
(для m ≤ x & lt; n). См. @Alex ответ для подробностей.
Если вы застряли с Java 6 (или Android 4.x), вам нужно использовать внешнюю библиотеку (например, org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1)
, см. ответ @mawaldne ) или реализовать свой собственный nextLong(n)
.
Согласно http://java.sun.com/j2se/ 1.5.0 / docs / api / java / util / Random.html nextInt
реализовано как
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
. Поэтому мы можем изменить это, чтобы выполнить nextLong
:
long nextLong(Random rng, long n) {
// error checking and 2^x checking removed for simplicity.
long bits, val;
do {
bits = (rng.nextLong() << 1) >>> 1;
val = bits % n;
} while (bits-val+(n-1) < 0L);
return val;
}
Отражение; для экземпляра:
obj.GetType().GetProperties();
для типа:
typeof(Foo).GetProperties();
, например:
class Foo {
public int A {get;set;}
public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
После обратной связи ...
null
в качестве первого аргумента для GetValue
GetProperties (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
(который возвращает все публичные / частные свойства экземпляра). Вы можете использовать Reflection , чтобы сделать это: (из моей библиотеки - это получает имена и значения)
public static Dictionary<string, object> DictionaryFromType(object atype)
{
if (atype == null) return new Dictionary<string, object>();
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (PropertyInfo prp in props)
{
object value = prp.GetValue(atype, new object[]{});
dict.Add(prp.Name, value);
}
return dict;
}
Эта вещь не будет работать для свойств с индексом - для этого (это становится громоздким):
public static Dictionary<string, object> DictionaryFromType(object atype,
Dictionary<string, object[]> indexers)
{
/* replace GetValue() call above with: */
object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
}
Кроме того, чтобы получить только открытые свойства: ( см. MSDN для перечисления BindingFlags )
/* replace */
PropertyInfo[] props = t.GetProperties();
/* with */
PropertyInfo[] props = t.GetProperties(BindingFlags.Public)
Это работает и для анонимных типов!
Чтобы просто получить имена:
public static string[] PropertiesFromType(object atype)
{
if (atype == null) return new string[] {};
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
List<string> propNames = new List<string>();
foreach (PropertyInfo prp in props)
{
propNames.Add(prp.Name);
}
return propNames.ToArray();
}
И это примерно то же самое только для значений, или вы можете использовать:
GetDictionaryFromType().Keys
// or
GetDictionaryFromType().Values
Но я думаю, что это немного медленнее.
Вы можете использовать пространство имен System.Reflection
с Type.GetProperties ()
метод:
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
Вы можете использовать отражение.
Type typeOfMyObject = myObject.GetType();
PropertyInfo[] properties =typeOfMyObject.GetProperties();