Для тех, кто не может полагаться на Chronometer , я сделал класс утилиты из одного из предложений:
public class TimerTextHelper implements Runnable {
private final Handler handler = new Handler();
private final TextView textView;
private volatile long startTime;
private volatile long elapsedTime;
public TimerTextHelper(TextView textView) {
this.textView = textView;
}
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
textView.setText(String.format("%d:%02d", minutes, seconds));
if (elapsedTime == -1) {
handler.postDelayed(this, 500);
}
}
public void start() {
this.startTime = System.currentTimeMillis();
this.elapsedTime = -1;
handler.post(this);
}
public void stop() {
this.elapsedTime = System.currentTimeMillis() - startTime;
handler.removeCallbacks(this);
}
public long getElapsedTime() {
return elapsedTime;
}
}
для использования.. просто делать:
TimerTextHelper timerTextHelper = new TimerTextHelper(textView);
timerTextHelper.start();
.....
timerTextHelper.stop();
long elapsedTime = timerTextHelper.getElapsedTime();
Вы можете использовать отражение.
Type typeOfMyObject = myObject.GetType();
PropertyInfo[] properties =typeOfMyObject.GetProperties();
Основываясь на ответе @ MarcGravell, вот версия, которая работает в Unity C #.
ObjectsClass foo = this;
foreach(var prop in foo.GetType().GetProperties()) {
Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null));
}
Вы можете использовать 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 enum )
/* 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
Но это немного медленнее, я бы представьте себе.
t.GetProperties(BindingFlags.Instance | BindingFlags.Public)
или t.GetProperties(BindingFlags.Static | BindingFlags.Public)
– Carl
6 May 2015 в 15:01
Вы можете использовать пространство имен System.Reflection
с помощью метода Type.GetProperties()
:
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
Здесь улучшен ответ @lucasjones. Я включил улучшения, упомянутые в разделе комментариев после его ответа. Я надеюсь, что кто-то найдет это полезным.
public static string[] GetTypePropertyNames(object classObject, BindingFlags bindingFlags)
{
if (classObject == null)
{
throw new ArgumentNullException(nameof(classObject));
}
var type = classObject.GetType();
var propertyInfos = type.GetProperties(bindingFlags);
return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToArray();
}
Это мое решение
public class MyObject
{
public string value1 { get; set; }
public string value2 { get; set; }
public PropertyInfo[] GetProperties()
{
try
{
return this.GetType().GetProperties();
}
catch (Exception ex)
{
throw ex;
}
}
public PropertyInfo GetByParameterName(string ParameterName)
{
try
{
return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName);
}
catch (Exception ex)
{
throw ex;
}
}
public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue)
{
try
{
obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue);
return obj;
}
catch (Exception ex)
{
throw ex;
}
}
}
yield return
. Это неважно, но это лучший способ сделать это.
– Matthew Haugen
24 July 2014 в 04:42
Отражение; для экземпляра:
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)
(который возвращает все свойства public / private экземпляра). internal
. Может быть, я единственный, кто повесил трубку на синтаксисе private
/ non-public
?
– brichins
9 August 2013 в 00:39
using System.Reflection
и System.Reflection.TypeExtensions
- это обеспечивает отсутствие поверхности API через методы расширения
– Marc Gravell♦
17 May 2017 в 09:18
Я также сталкиваюсь с таким требованием.
Из этого обсуждения я получил еще одну идею,
Obj.GetType().GetProperties()[0].Name
Это также показывает имя свойства.
Obj.GetType().GetProperties().Count();
, показывающий количество свойств.
Спасибо всем. Это приятное обсуждение.